androidmediarecordercamera-api

MediaRecorder gives start error or IllegalStateException


I am using MediaRecorder for recording a video through Camera API of android. I am stucked with a very strange problem.

    private void startRecordingVideo() {
    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
    File file = getAlbumDir();
    recorder.setOutputFile(file.getAbsolutePath());
    recorder.setMaxDuration(50000);
    recorder.setMaxFileSize(5000000);
    recorder.setPreviewDisplay(CameraBridgeViewBase.surfaceHolder.getSurface());
    try {
        recorder.prepare();
        recorder.start();
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
    }     
}

Now this gives me MediaRecorder: start failed: -19 error. I have checked this and this links which says to remove mediaRecorder.setVideoSize(sView.getWidth(), sView.getHeight()); but I didn't usesetVideoSize(sView.getWidth(), sView.getHeight()). With try and error I found that if I remove encoders recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); and recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT); app doesn't crash but gives new exception as:

03-23 16:50:06.213 28226-28226/com.scenera.android.surveillance E/MediaRecorder: audio source is set, but audio encoder is not set

I don't understand what I am doing wrong here. Any help would be appriciated. Thanks in advance.


Solution

  • The problem is that you're not setting the camera, using Camera 1 API you should first open the camera, then unlock it and set it to the recorder. Only after that you can continue with the configuration of MediaRecorder (which is btw a very beautifully written piece of API)

    MediaRecorder recorder = new MediaRecorder();
    
    Camera camera = Camera.open();
    camera.unlock();
    recorder.setCamera(camera);
    recorder.setPreviewDisplay(surfaceHolder.getSurface());
    
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    
    recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
    
    File file = getAlbumDir();
    recorder.setOutputFile(file.getAbsolutePath());
    
    recorder.setMaxDuration(50000);
    recorder.setMaxFileSize(5000000);
    try {
        recorder.prepare();
        recorder.start();
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
    }