android教程之MediaPlayer和MediaRecorder

这是我看到的讲解很细致的国外教程。
现在转过来,希望对大家有所帮助。
         Androidsupport Media API as optional APIs. The media APIs providefunctionality of playing and recording audio files and video files. Intoday’s post we will see how to play and record audio files.
Playing Audio File:
Androidhas defined a MediaPlayer class for playing media file. This class canbe used to play the audio files. The class provides static methods tocreate the instance of the media player. Here is how the MediaPlayerobject can be obtained using create methods
  1. MediaPlayer.create(context, Uri.parse(”file:///sdcard/audio_file.mp3″);
复制代码

and
  1. MediaPlayer.create(context, R.raw.song_file);
复制代码

Thefirst create methods gets the Uri for the audio file and can be used toplay files present on the phone sdcard. The second create method usethe application resource file song_file.mp3. The song_file.mp3 file isadded as a raw resource under res/raw directory.
Notethat if the MediaPlayer object does not get created successfully, thecreate methods will return null so it will be better to check for thereturn object for null value to avoid NullPointer exception.
TheMediaPlayer object can also be obtained by instantiating usingMediaPlayer constructor. The object created like this has to beinitialized with the file that needs to be played. setDataSource()method can be used to initialize the object with the audio file.
  1. MediaPlayer mediaPlayer = new MediaPlayer();
  2. try {
  3. mediaPlayer.setDataSource(”/sdcard/audio_file.mp3″); // provide path to the file.
  4. } catch (IllegalArgumentException e) {
  5. // handle exception
  6. } catch (IllegalStateException e) {
  7. // handle exception
  8. } catch (IOException e) {
  9. // handle exception
  10. }
  11. Ifyou want to send the media player object with one of the files fromapplication raw resources or from application assets files you can dothat as follows:
  12. try {
  13. AssetFileDescriptor fd = getResources().openRawResouceFd(R.raw.song_file);
  14. mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
  15. fd.close();
  16. } catch (IllegalArgumentException e) {
  17. // handle exception
  18. } catch (IllegalStateException e) {
  19. // handle exception
  20. } catch (IOException e) {
  21. // handle exception
  22. }
复制代码

TheMediaPlayer object has to be prepared before the player can startplaying the song. The prepare() method is the blocking method andblocks until the media player is ready to play the song. One nonblocking method prepareAsync() is also provided. The non blockingprepare method should be used in case media player is used to play asong from a stream and need to buffer data before song can be played.The create methods that we saw earlier call the prepare() method andapplication must not call it again. To start file playback use start()method. This is how you play a file:
  1. MediaPlayer mediaPlayer = new MediaPlayer();
  2. try {
  3. mediaPlayer.setDataSource(”/sdcard/audio_file.mp3″); // provide path to the file.
  4. mediaPlayer.prepare();
  5. } catch (IllegalArgumentException e) {
  6. // handle exception
  7. } catch (IllegalStateException e) {
  8. // handle exception
  9. } catch (IOException e) {
  10. // handle exception
  11. }
复制代码

mediaPlayer.start();
Thefile playback can be pause with pause() method, and can be resumes withstart method. The file playback can be stopped with stop() method. Themedia player object has to reset before it can be setup for some othersong file. The media player object has to be released after its use.
AndroidMedia API defines some listeners like OnCompletionListener,OnPrepareListener, OnErrorListener, OnBufferingUpdateListener
OnCompletionListenerevent gets fired when media player complete the playing of the currentaudio file. You can use this listener event for playing next song fromthe list or releasing the media player object.
OnPrepareListeneris needed when prepareAsync method is used. Since the prepareAsyncmethod does not block for the call duration, the application can notstart playing the song. The onPrepared() event function will be calledonce the media player is ready. You can start playing the song in theonPrepared() method.
OnErrorListeneris also used in case of asynchronous operations. If any error occurs inasynchronous operation, onError() method of this listener will becalled.
Recording Audio Files:
TheMedia API also provides functionality to record audio files. TheMediaRecorder class can be used for media recording. The MediaRecorderhas to be initialized with the Audio Encoder, output format (codec tobe used for recorded file), Audio Source (like Microphone) and outputfile path where the recorded file will be stored. Here is how recordingcan be done:
  1. MediaRecorder recorder = new MediaRecorder();
  2. recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  3. recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
  4. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  5. recorder.setOutputFile(filePath); // complete file path
  6. recorder.prepare();
  7. recorder.start();
复制代码

Thiswill start the recording the recording can be stored with stop()method. The MediaRecorder object also needs to be release after its use.
That all for today’s post. We will see Media APIs Video support in some other post.
ResourceThemeAudioVideoAPI
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值