我尝试使用来自android.developers网站的代码构建一个使用MediaPlayer
录制视频的应用。但是,当我在我的设备中打开它时,它说不幸的是应用程序需要关闭。但是当我在模拟器上运行它时,我可以看到它的工作原理(使用日志)。这是MainActivity
代码。
package com.example.camcorder_mediaplayer;
import java.io.IOException;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity implements OnClickListener,
SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
public static final String TAG = "VIDEOCAPTURE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
recorder = new MediaRecorder();
initrecorder();
setContentView(R.layout.activity_main);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
}
private void initrecorder() {
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHig = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/videocapture_example.mp4");
recorder.setMaxDuration(50000);
recorder.setMaxFileSize(5000000);
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void surfaceChanged(SurfaceHolder arg0,int arg1,int arg2,int arg3){}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "Surface Created");
prepareRecorder();
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.v(TAG, "Surface deleed");
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
finish();
}
@Override
public void onClick(View arg0) {
if (recording) {
recorder.stop();
recording = false;
// recorder.release()
Log.v(TAG, "Recording stopped");
initrecorder();
prepareRecorder();
} else {
recording = true;
recorder.start();
Log.v(TAG, "Recording started");
}
}
}