1. 程式人生 > >setOutputFormat called in an invalid state: 1

setOutputFormat called in an invalid state: 1

style sdc display run -c con evel eve htm

在編寫一個簡單的錄像應用程序的時候,爆出例如以下異常:

E MediaRecorder: setOutputFormat called in an invalid state: 1
E AndroidRuntime: java.lang.IllegalStateException
E AndroidRuntime: at android.media.MediaRecorder.setOutputFormat(Native Method)


由於code是全然依照google的Demo寫的,認為比較奇怪。

看描寫敘述是說setOutputFormat的時候,狀態應該錯亂了。最後又看了一下google文檔,原因在於google對於設定MediaRecorder是有要求的:

技術分享圖片

所以在寫代碼的時候應該全然依照人家要求的設定順序來寫,詳細例如以下:

    	mCamera.unlock();
    	mProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
    	
    	//1st. Initial state
    	mMediaRecorder = new MediaRecorder();
    	mMediaRecorder.setCamera(mCamera);
    	
    	//2st. Initialized state
    	mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    	mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    	
    	//3st. config
        mMediaRecorder.setOutputFormat(mProfile.fileFormat);
        mMediaRecorder.setAudioEncoder(mProfile.audioCodec);
        mMediaRecorder.setVideoEncoder(mProfile.videoCodec);
        mMediaRecorder.setOutputFile("/sdcard/FBVideo.3gp");
        mMediaRecorder.setVideoSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight);
        mMediaRecorder.setVideoFrameRate(mProfile.videoFrameRate);
        mMediaRecorder.setVideoEncodingBitRate(mProfile.videoBitRate);
        mMediaRecorder.setAudioEncodingBitRate(mProfile.audioBitRate);
        mMediaRecorder.setAudioChannels(mProfile.audioChannels);
        mMediaRecorder.setAudioSamplingRate(mProfile.audioSampleRate);

    	
    	mMediaRecorder.setPreviewDisplay(mHolder.getSurface());
    	
    	try {
			mMediaRecorder.prepare();
			mMediaRecorder.start();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


setOutputFormat called in an invalid state: 1