我们公司有业务要需要做限制拍摄时间的视频录制功能,官方提供的API太坑 太坑 太坑 太坑,压根不能用
感谢这位同行分享的代码:
https://ask.dcloud.net.cn/question/25816?item_id=108332&rf=false
我基于该分享的代码进行改进,成功在本地存储了mp4文件,望对大家有帮助
var Camera = plus.android.importClass('android.hardware.Camera')
,MediaRecorder = plus.android.importClass('android.media.MediaRecorder')
,SurfaceView = plus.android.importClass('android.view.SurfaceView')
,LinearLayout = plus.android.importClass('android.widget.LinearLayout')
,MediaRecorder = plus.android.importClass('android.media.MediaRecorder')
,SurfaceHolder = plus.android.implements('android.view.SurfaceHolder');
var mainActivity = plus.android.runtimeMainActivity()
,cameraView = new LinearLayout(mainActivity)
,surfaceView = new SurfaceView(mainActivity)
,cameraCount = Camera.getNumberOfCameras()
,cameraInfo = new Camera.CameraInfo()
,mediaRecorder = new MediaRecorder()
,cameraId = null
,camera = null
,surfaceHolder = null
,videoFilePath = plus.io.convertLocalFileSystemURL('_downloads/') + Date.now() + '.mp4';
//查询可用摄像头
for (var i = 0;i < cameraCount;i++) {
Camera.getCameraInfo(i, cameraInfo);
if(plus.android.getAttribute(cameraInfo, 'facing') !== cameraInfo.CAMERA_FACING_BACK) continue;
cameraId = i;
break;
}
if(cameraId === null) throw Error('无后置摄像头');
cameraView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
cameraView.addView(surfaceView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
mainActivity.setContentView(cameraView);
camera = Camera.open(cameraId);
camera.setDisplayOrientation(90);
camera.unlock();
surfaceHolder = surfaceView.getHolder();
mediaRecorder.setCamera(camera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setVideoSize(1280, 720);
mediaRecorder.setVideoFrameRate(20);
mediaRecorder.setPreviewDisplay(plus.android.invoke(surfaceHolder, 'getSurface'));
mediaRecorder.setOutputFile(videoFilePath);
mediaRecorder.prepare();
mediaRecorder.start();
//camera.release();
setTimeout(function(){
mediaRecorder.stop();
camera.release();
}, 3e3);