2011年5月17日火曜日

AndroidStudyMemo=Working with Audio

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 AndroidManifest.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 ContentResolver 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

BroadcastIntent 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.

 

0 件のコメント:

コメントを投稿