Android Studio录制视频源码
时间: 2023-12-05 17:41:51 浏览: 86
以下是Android Studio录制视频的源码示例:
1. 在XML布局文件中添加一个SurfaceView和一个Button:
```xml
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/btnRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record" />
```
2. 在Activity中实现SurfaceHolder.Callback接口,并在onCreate()方法中设置SurfaceView的回调:
```java
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private Camera mCamera;
private SurfaceView mSurfaceView;
private SurfaceHolder mHolder;
private boolean isRecording = false;
private Button mBtnRecord;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = findViewById(R.id.surfaceView);
mBtnRecord = findViewById(R.id.btnRecord);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mHolder.getSurface() == null) {
return;
}
try {
mCamera.stopPreview();
} catch (Exception e) {
e.printStackTrace();
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
```
3. 在Button的点击事件中实现视频录制功能:
```java
mBtnRecord.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isRecording) {
mCamera.stopPreview();
mBtnRecord.setText("Record");
isRecording = false;
} else {
mCamera.unlock();
MediaRecorder recorder = new MediaRecorder();
recorder.setCamera(mCamera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
recorder.setOutputFile(getOutputMediaFile().toString());
recorder.setPreviewDisplay(mHolder.getSurface());
try {
recorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
mBtnRecord.setText("Stop");
isRecording = true;
}
}
});
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
}
```
阅读全文