Android MediaRecorder录制视频提示start failed的解决办法
转自https://blog.csdn.net/w815878564/article/details/49247411
今天测试MediaRecorder录制功能的时候出现一个蛋疼的BUG,按照官方提供的示例写好之后,start居然报错,打印日志一看说:start failed。
代码如下:
- mCamera = Camera.open(0);
- surfaceView = new SurfaceView(this);
- setContentView(surfaceView);
- mSurfaceHolder = surfaceView.getHolder();
- mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
- mRecorder = new MediaRecorder();
- mRecorder.setCamera(mCamera);
- mRecorder.setAudioSource(AudioSource.DEFAULT);
- mRecorder.setVideoSource(VideoSource.DEFAULT);
- mRecorder.setOutputFormat(OutputFormat.MPEG_4);
- mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
- mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
- mRecorder.setVideoSize(320, 240);
- mRecorder.setVideoFrameRate(20);
- mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
- File file = new File(Environment.getExternalStorageDirectory()
- .getAbsolutePath() + "/test.mp4");
- if (file.exists())
- {
- file.delete();
- }
- try
- {
- file.createNewFile();
- } catch (IOException e1)
- {
- e1.printStackTrace();
- }
- mRecorder.setOutputFile(file.getAbsolutePath());
- mSurfaceHolder.addCallback(new Callback()
- {
- @Override
- public void surfaceDestroyed(SurfaceHolder holder)
- {
- }
- @Override
- public void surfaceCreated(SurfaceHolder holder)
- {
- try
- {
- mRecorder.prepare();
- mRecorder.start();
- } catch (Exception e)
- {
- Writer writer = new StringWriter();
- PrintWriter printWriter = new PrintWriter(writer);
- e.printStackTrace(printWriter);
- Throwable cause = e.getCause();
- while (cause != null)
- {
- cause.printStackTrace(printWriter);
- cause = cause.getCause();
- }
- String str = writer.toString();
- System.out.println(str);
- }
- }
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format,
- int width, int height)
- {
- }
- });
一般情况下呢,出现这个原因是由于系统不支持你所设置的分辨率码率这些参数,因此首先需要检查系统是否支持你所设置的参数,参数可以通过Camera的Parameter来进行判断,调用如下:
- mCamera.getParameters().getSupportedVideoSizes()
但是有时候即使设置了正确的参数仍旧会出现这个错误,这时候可能你就需要再start之前调用一下下面这个方法了:
- mCamera.unlock();
这个方法从方法名来看 是解锁Camera 估计是怕使用设备冲突了把 ,具体原因以后有空再去看看Camera相关API说明。因此对于这种情况 我觉得最好的做法是在获取到Camera对象之后 进行一下如下操作:
- mCamera.stopPreview();
- mCamera.setPreviewCallback(null);
- mCamera.setPreviewCallbackWithBuffer(null);
- mCamera.release();
- mCamera = null;
- mCamera = Camera.open(0);
- mCamera.lock();
- mCamera.unlock();