使用MediaRecorder能够通过麦克风和相机捕获音视频并保存
相关权限
1 2 3 4 5 6 7 8 9 10
| <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.CAMERA"/>
|
动态申请就不放了,太长
调用摄像头录制
布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center">
<TextureView android:layout_weight="1" android:id="@+id/media_textureView" android:layout_width="match_parent" android:layout_height="match_parent"/> <Button android:text="开始录制" android:id="@+id/media_btn1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
|
在按钮的点击事件中设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| media_btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String btnText = media_btn1.getText().toString(); if (btnText.equals("开始录制")){ media_btn1.setText("结束录制");
camera = Camera.open();
camera.setDisplayOrientation(90); camera.unlock();
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setOrientationHint(90);
mediaRecorder.setOutputFile(new File(getExternalFilesDir(""),"test.mp4").getAbsolutePath());
mediaRecorder.setVideoSize(1280,720);
mediaRecorder.setVideoFrameRate(60);
mediaRecorder.setPreviewDisplay(new Surface(media_textureView.getSurfaceTexture())); try {
mediaRecorder.prepare(); } catch (IOException e) { e.printStackTrace(); }
mediaRecorder.start(); } else { media_btn1.setText("开始录制");
mediaRecorder.stop();
mediaRecorder.release();
camera.stopPreview(); camera.release(); } } });
|
效果图