轉自https://blog.csdn.net/w815878564/article/details/49247411java
今天測試MediaRecorder錄製功能的時候出現一個蛋疼的BUG,按照官方提供的示例寫好以後,start竟然報錯,打印日誌一看說:start failed。ide
代碼以下:測試
- 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來進行判斷,調用以下:this
- mCamera.getParameters().getSupportedVideoSizes()
可是有時候即便設置了正確的參數仍舊會出現這個錯誤,這時候可能你就須要再start以前調用一下下面這個方法了:spa
這個方法從方法名來看 是解鎖Camera 估計是怕使用設備衝突了把 ,具體緣由之後有空再去看看Camera相關API說明。所以對於這種狀況 我以爲最好的作法是在獲取到Camera對象以後 進行一下以下操做:.net
- mCamera.stopPreview();
- mCamera.setPreviewCallback(null);
- mCamera.setPreviewCallbackWithBuffer(null);
- mCamera.release();
- mCamera = null;
- mCamera = Camera.open(0);
- mCamera.lock();
- mCamera.unlock();