MediaRecorder
MediaRecorder使用来录制视频和音频常见的类,关于其的内容还是较为简单易学的,主要是针对其录制视频和音频的方法来熟悉这个类,并设置常见的参数。
音频录制
1.创建MediaRecorder的实例;
2.setAudioSource;设置音频的来源
3.setOutputFormat();设置输出格式
4.setAudioEncoder():设置音频的编码
5.setOutFile():设置生成文件
6.prepare:准备工作
7.start():开始录制
8.stop()/reset():结束
9.release():释放资源
public class MainActivity extends AppCompatActivity {
private Button recordAudio;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recordAudio = (Button) findViewById(R.id.record_audio);
recordAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recordAudio();
}
});
}
//录制音频
private void recordAudio() {
MediaRecorder audioRecorder = new MediaRecorder();
audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
audioRecorder.setOutputFile(getExternalCacheDir().getAbsolutePath()+"/audioRecord");
try {
//3s 自动结束
audioRecorder.setMaxDuration(3000);
audioRecorder.prepare();
audioRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
录制视频
1.实例MediaCoder的例子
2.setVideoSource(): 设置视频来源
3.setOutputFormat():设置输出的格式
4.setVideoEncoder():设置视频编码
5.setVideoSize():设置视频的宽和高
6.setVideFrameRate:设置视频帧率
7.setPreviewDisplay:设置预览的界面
8.prepare():准备
9.start():开始录制
10.stop/reset:停止录制
11.release:释放资源
private void recordVideo() {
videoRecorder = new MediaRecorder();
videoRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
videoRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
videoRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
videoRecorder.setOutputFile(getExternalCacheDir().getAbsolutePath() + "/videoRecord");
videoRecorder.setVideoSize(640, 480);
videoRecorder.setVideoFrameRate(20);
videoRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
try {
videoRecorder.setMaxDuration(8000);
videoRecorder.prepare();
videoRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
encode和outputFormat的对应关系
https://developer.android.com/guide/appendix/media-formats.html
video:
image:
audio:
CamcorderProfile
我们可以直接设此参数,从而不需要设置一个帧率,编码,输出格式等参数。
private void recordVideo(int type) {
videoRecorder = new MediaRecorder();
videoRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
videoRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_1080P);
videoRecorder.setProfile(camcorderProfile);
videoRecorder.setOutputFile(getExternalCacheDir().getAbsolutePath() + "/videoRecord_type");
videoRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
videoRecorder.setMaxDuration(10000);
try {
videoRecorder.prepare();
videoRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
关于MediaRecorder就介绍这么多了