要實現拍照和錄像功能,可以使用Android的Camera類和MediaRecorder類來實現。
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private MediaRecorder mMediaRecorder;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
}
);
Button recordButton = (Button) findViewById(R.id.button_record);
recordButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isRecording) {
stopRecording();
} else {
startRecording();
}
}
}
);
}
private Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open();
}
catch (Exception e){
Log.e(TAG, "Failed to open camera: " + e.getMessage());
}
return c;
}
private void startRecording(){
mCamera.unlock();
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
try {
mMediaRecorder.prepare();
mMediaRecorder.start();
} catch (IOException e) {
Log.e(TAG, "Failed to start recording: " + e.getMessage());
}
}
private void stopRecording(){
mMediaRecorder.stop();
mMediaRecorder.reset();
mMediaRecorder.release();
mMediaRecorder = null;
mCamera.lock();
}
private PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
//保存拍照圖片的邏輯
}
};
}
在以上代碼中,需要自定義CameraPreview類來顯示相機預覽,具體實現可以參考Android官方文檔。同時,需要實現獲取輸出文件路徑的方法getOutputMediaFile()來保存拍照和錄像的文件。