Working with Audio Android

Much like video, the Android SDK provides methods for audio playback and recording. Audio files can be resources, local files, or Uri objects to shared or network resources. Audio recording takes place through the built-in microphone on the device, if one is present (typically a requirement for a phone because one speaks into it quite often).

Recording Audio

The MediaRecorder object of the Android SDK provides audio recording functionality. Using it is a matter of following a few simple steps you should now find familiar:

  1. Instantiate a new MediaRecorder object.
  2. Set the audio source.
  3. Set the audio format to record with.
  4. Set the file format to store the audio in.
  5. Set the file to record to.
  6. Prepare the object for recording.
  7. Start the recording.
  8. Stop and release the recording object when finished.

Using a couple simple buttons, you can create a simple Activity to record and play back audio using the preceding steps. The onClick() method for a record button might look like this:

public void onClick(View v) {
if (audioRecorder == null) {
audioRecorder = new MediaRecorder();
}
String pathForAppFiles =
getFilesDir().getAbsolutePath();
pathForAppFiles += RECORDED_FILE;
audioRecorder.setAudioSource(
MediaRecorder.AudioSource.MIC);
audioRecorder.setOutputFormat(
MediaRecorder.OutputFormat.DEFAULT);
audioRecorder.setAudioEncoder(
MediaRecorder.AudioEncoder.DEFAULT);
audioRecorder.setOutputFile(pathForAppFiles);
audioRecorder.prepare();
audioRecorder.start();
// button handling and other behavior here
}

The audioRecorder object is instantiated, if necessary. The default values for the recording source and output file work fine for our purposes. Of note are the values for CAMCORDER, which uses a microphone in the direction of the camera, and various voice values that can be used to record calls (beware of local laws) and choose the proper microphone for voice recognition uses.

A stop button is configured with an onClick() handler that looks like this:

public void onClick(View v) {
if (audioRecorder != null) {
audioRecorder.stop();
audioRecorder.release();
audioRecorder = null;
}
// button handling and other behavior here
}

Finally, applications wanting to record audio require the explicit permission android. permission. RECORD_ AUDIO set within the Android Manifest.xml file.

Now it is time to add the playback functionality, so we can listen to the audio we just recorded.

Playing Audio

The MediaPlayer object can be used to play audio. The following steps are required to prepare a file for playback:

  1. Instantiate a new MediaPlayer object.
  2. Set the path to the file using the setDataSource method.
  3. Call the prepare() method of the MediaPlayer object.
  4. Call the start() method to begin playback.
  5. Playback can then be stopped with a call to the stop() method.

The onClick() handler for a button to play the recorded audio from the previous example might look like the following:

public void onClick(View v) {
if (player == null) {
player = new MediaPlayer ();
}
try {
String audioFilePath =
getFilesDir().getAbsolutePath();
audioFilePath += RECORDED_FILE;
player.setDataSource(audioFilePath);
player.prepare();
player.start();
} catch (Exception e) {
Log.e(“Audio”, “Playback failed.”, e);
}
}

The audio data source can be a local file path, valid file object, or valid Uri to an audio resource. You can programmatically stop the sound playback by a call to the stop() method. You can set a MediaPlayer.OnCompletionListener object to get a callback when the playback finishes. When done with the MediaPlayer object, you should use a call to the release() method to free up any resources it might be using, much like the releasing of the MediaRecorder object.

Sharing Audio
Audio can be shared with the rest of the system. The Content Resolver can send the file to the MediaStore content provider. The following code snippet shows how to configure an audio entry in the audio library on the device:

ContentValues values = new ContentValues(9);

values.put(MediaStore.MediaColumns.TITLE, “RecordedAudio”);
values.put(MediaStore.Audio.Media.ALBUM,
“Your Groundbreaking Album”);
values.put(MediaStore.Audio.Media.ARTIST, “Your Name”);
values.put(MediaStore.Audio.Media.DISPLAY_NAME,
“The Audio File You Recorded In Media App”);
values.put(MediaStore.Audio.Media.IS_RINGTONE, 1);
values.put(MediaStore.Audio.Media.IS_MUSIC, 1);
values.put(MediaStore.MediaColumns.DATE_ADDED,
System.currentTimeMillis() / 1000);
values.put(MediaStore.MediaColumns.MIME_TYPE, “audio/mp4”);
values.put(MediaStore.Audio.Media.DATA, pathForAppFiles);
Uri audioUri = getContentResolver().insert(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
if (audioUri == null) {
Log.d(“Audio”, “Content resolver failed”);
return;
}

Setting these values enables the recorded audio to be used by different audio-oriented applications on the handset. For example, setting the IS_MUSIC flag enables the audio file to appear in the various sections of the music player and be sorted by its Album information. Setting the IS_RINGTONE flag enables the audio file to appear in the list of ringtones for the device.

Periodically, the handset scans for new media files. However, to speed up this process, a Broadcast Intent can be sent telling the system about new audio files. The following code demonstrates this for the audio added to the content library:

sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,audioUri));

After this broadcast Intent is handled, the audio file immediately appears in the designated applications.

Searching for Multimedia

You can use the search intent called android.intent.action.MEDIA_SEARCH to search for multimedia on a given device. You can also register an intent filter with your application to show up as a source for multimedia with this action. For example, you could perform a search for a specific artist and song like this:

Intent searchMusic = new Intent(
android.provider.MediaStore.INTENT_ACTION_MEDIA_SEARCH);
searchMusic.putExtra(android.provider.MediaStore.EXTRA_MEDIA_ARTIST,
“Cyndi Lauper”);
searchMusic.putExtra(android.provider.MediaStore.EXTRA_MEDIA_TITLE,
“I Drove All Night”);
searchMusic.putExtra(android.provider.MediaStore.EXTRA_MEDIA_FOCUS,
“audio/*”);
startActivity(searchMusic);

If you load up a bunch of music on your device (such as Cyndi Lauper’s “I Drove All Night”) and launch this intent, you are then directed straight to the song you requested. Note that if you have many music apps installed, you might need to select an appropriate one (such as the Music application) the first time you send the Intent.

Working with Ringtones

Much like wallpapers, ringtones are a popular way to personalize a handset. The Android SDK provides a variety of ways to manage ringtones through the Ringtone Manager object. You can assign the recorded audio from the previous example as the current ringtone with the following static method call:

RingtoneManager.setActualDefaultRingtoneUri(
getApplicationContext(),
RingtoneManager.TYPE_RINGTONE, audioUri);

The type can also be TYPE_ALARM or TYPE_NOTIFICATION to configure sounds of other system events that use audio tones. To successfully perform this operation, though, the application must have the android.permission.WRITE_SETTINGS permission set in the AndroidManifest.xml file. You can also query the default ringtone with a call to the static RingtoneManager.getActualDefaultRingtoneUri() method. You can use the resulting Uri to play the ringtone, which might be useful within applications that want to alert the user.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Android Topics