AndroidManifest.xml中添加权限标记
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
动态添加权限MainActivity
requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO},100);
创建MediaRecordActivity,使用Intent连接MainActivity和MediaRecordActivity
startActivity(new Intent(this,MediaRecordActivity.class));
MediaRecordActivity中设置MediaRecorder
@Overridepublic void onClick(View view) {CharSequence text =btn_opt.getText();if (TextUtils.equals(text,"开始")){btn_opt.setText("结束");camera = Camera.open(); //原始Android Camera类已废弃。应使用CameraX(推荐)或Camera2camera.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(""),"b.mp4").getAbsolutePath());mediaRecorder.setVideoSize(640,480);mediaRecorder.setPreviewDisplay(new Surface(textureView.getSurfaceTexture()));try {mediaRecorder.prepare();} catch (IOException e) {e.printStackTrace();}mediaRecorder.start();}else {btn_opt.setText("开始");mediaRecorder.stop();mediaRecorder.release();camera.stopPreview();camera.release();}}
MediaRecorder状态图
MediaRecorder详细请参考
MediaRecorder 概览 | Android media | Android Developers (google.cn)
MediaRecorder | Android Developers (google.cn)