我需要将视频文件录制到mp4格式。但是,当我运行并单击记录按钮时,它会抛出错误,如 FATAL EXCEPTION:main java.lang.IllegalStateException 。 这是我的整个代码
boolean recording = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_example);
initUI();
initRecorder();
buttonStopVid.setEnabled(false);
buttonPlayVid.setEnabled(false);
buttonStartVid.setOnClickListener(this);
holder = surfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
protected void initUI(){
buttonStartVid = (Button) findViewById(R.id.buttonStartRecordVid);
buttonPlayVid = (Button) findViewById(R.id.buttonPlayVid);
buttonStopVid = (Button) findViewById(R.id.buttonStopRecordVid);
videoView = (VideoView) findViewById(R.id.videoView);
surfaceView = (SurfaceView) findViewById(R.id.surface_camera_final);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.buttonStartRecordVid){
buttonStartVid.setEnabled(false);
buttonStopVid.setEnabled(true);
surfaceView.setVisibility(View.VISIBLE);
prepareRecorder();
recording = true;
recorder.start();
}
if(v.getId() == R.id.buttonStopRecordVid){
buttonPlayVid.setEnabled(true);
buttonStartVid.setEnabled(true);
buttonStopVid.setEnabled(false);
surfaceView.setVisibility(View.GONE);
recorder.stop();
recording = false;
initRecorder();
prepareRecorder();
}
if(v.getId() == R.id.buttonPlayVid){
}
}
protected void initRecorder(){
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cp = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cp);
try{
File newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
}
catch (IOException e){
e.printStackTrace();
}
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(recording){
recorder.stop();
recording = false;
}
recorder.release();
}
任何可能导致此问题以及如何解决问题的想法?谢谢!
答案 0 :(得分:1)
使用此链接 http://developer.android.com/reference/android/media/MediaRecorder.html
它将提供您需要的完整信息。
答案 1 :(得分:0)
看起来你的prepareRecorder()函数会被多次调用,这会导致MediaRecorder抛出illegalState异常。 MediaRecorder有你需要记住的状态机。你需要知道你的MediaRecorder是哪个州,然后做相应的过程。从您的异常日志中,它说MediaRecorder在错误的状态下执行错误的进程。我认为http://developer.android.com/reference/android/media/MediaRecorder.html可能是一个很好的文档。