Android多媒体之音频、视频录制MediaRecorder

概述:

MediaRecorder的状态图:

Initial:初始状态,当使用new()方法创建一个MediaRecorder对象或者调用了reset()方法时,该MediaRecorder对象处于Initial状态。在设定视频源或者音频源之后将转换为Initialized状态。另外,在除Released状态外的其它状态通过调用reset()方法都可以使MediaRecorder进入该状态。

Initialized:已初始化状态,可以通过在Initial状态调用setAudioSource()或setVideoSource()方法进入该状态。在这个状态可以通过setOutputFormat()方法设置输出格式,此时MediaRecorder转换为DataSourceConfigured状态。另外,通过reset()方法进入Initial状态。

DataSourceConfigured:数据源配置状态,这期间可以设定编码方式、输出文件、屏幕旋转、预览显示等等。可以在Initialized状态通过setOutputFormat()方法进入该状态。另外,可以通过reset()方法回到Initial状态,或者通过prepare()方法到达Prepared状态。

Prepared:就绪状态,在DataSourceConfigured状态通过prepare()方法进入该状态。在这个状态可以通过start()进入录制状态。另外,可以通过reset()方法回到Initialized状态。

Recording:录制状态,可以在Prepared状态通过调用start()方法进入该状态。另外,,它可以通过stop()方法或reset()方法回到Initial状态。

Released:释放状态(官方文档给出的词叫做Idle state 空闲状态),可以通过在Initial状态调用release()方法来进入这个状态,这时将会释放所有和MediaRecorder对象绑定的资源。

Error:错误状态,当错误发生的时候进入这个状态,它可以通过reset()方法进入Initial状态。

提示:与MediaPlayer相似使用MediaRecorder录音录像时需要严格遵守状态图说明中的函数调用先后顺序,在不同的状态调用不同的函数,否则会出现异常。

代码:

开始录制音频:

mRecorder = new MediaRecorder();//Sets the audio source to be used for recording,设置音频资源mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//Sets the format of the output file produced during recording,设置输出音频的格式mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//Sets the video encoder to be used for recording,设置音频编码格式mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//Sets the path of the output file to be produced,设置音频文件输出路径mRecorder.setOutputFile(Environment.getExternalStorageDirectory() + “/my_recorder.3gp”);try {//Prepares the recorder to begin capturing and encoding datamRecorder.prepare();//Begins capturing and encoding data to the file specified with setOutputFile()mRecorder.start();} catch (IOException e) {e.printStackTrace();}

停止录制音频

//Stops recordingmRecorder.stop();//Restarts the MediaRecorder to its idle statemRecorder.reset();//Releases resources associated with this MediaRecorder object,释放资源mRecorder.release();

需要在manifests中申请权限:

>>

怎么能研究出炸药呢?爱迪生不经历上千次的来自失败,怎么能发明电灯呢?

Android多媒体之音频、视频录制MediaRecorder

相关文章:

你感兴趣的文章:

标签云: