转自https://blog.csdn.net/w815878564/article/details/49247411
今天测试MediaRecorder录制功能的时候出现一个蛋疼的BUG,按照官方提供的示例写好之后,start居然报错,打印日志一看说:start failed。
代码如下:
[java] view plain copy
- 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来进行判断,调用如下:
[java] view plain copy
- mCamera.getParameters().getSupportedVideoSizes()
但是有时候即使设置了正确的参数仍旧会出现这个错误,这时候可能你就需要再start之前调用一下下面这个方法了:
[java] view plain copy
- mCamera.unlock();
这个方法从方法名来看 是解锁Camera 估计是怕使用设备冲突了把 ,具体原因以后有空再去看看Camera相关API说明。因此对于这种情况 我觉得最好的做法是在获取到Camera对象之后 进行一下如下操作:
[java] view plain copy
- mCamera.stopPreview();
- mCamera.setPreviewCallback(null);
- mCamera.setPreviewCallbackWithBuffer(null);
- mCamera.release();
- mCamera = null;
- mCamera = Camera.open(0);
- mCamera.lock();
- mCamera.unlock();
原文地址:https://www.cnblogs.com/yangjies145/p/9038279.html
时间: 2024-10-29 04:14:57