MediaRecorder
Android用这个类来录制音频和视频,官方说明文档:Used to record audio and video. The recording control is based on a simple state machine.
录制音频的示例代码
val recorder = MediaRecorder()
recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
recorder.setOutputFile(PATH_NAME)
recorder.prepare()
recorder.start()
结束录制的示例代码
recorder.stop()
recorder.reset() // 将MediaRecorder设为空闲状态,即Initial状态。重复上面setAudioSource等一系列方法,你可以复用这个recorder对象来再次录制
recorder.release() // 执行完这个方法,这个recorder对象不再可用
提供了方便的监听方法
interface OnInfoListener {
/**
* Called to indicate an info or a warning during recording.
*
* @param mr the MediaRecorder the info pertains to
* @param what the type of info or warning that has occurred
*
* * [.MEDIA_RECORDER_INFO_UNKNOWN]
* * [.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED]
* * [.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED]
*
* @param extra an extra code, specific to the info type
*/
fun onInfo(mr: MediaRecorder?, what: Int, extra: Int)
}
interface OnErrorListener {
/**
* Called when an error occurs while recording.
*
* @param mr the MediaRecorder that encountered the error
* @param what the type of error that has occurred:
*
* * [.MEDIA_RECORDER_ERROR_UNKNOWN]
* * [.MEDIA_ERROR_SERVER_DIED]
*
* @param extra an extra code, specific to the error type
*/
fun onError(mr: MediaRecorder?, what: Int, extra: Int)
}
添加监听对象
// Register a callback to be invoked when an error occurs while recording.
recorder.setOnErrorListener(Listener)
// Register a callback to be invoked when an informational event occurs while recording.
recorder.setOnInfoListener(Listener)