使用 Android Camera API 完成音視頻的采集硼啤、編碼嗓袱、封包成 mp4 輸出
基于android.hardware.Camera蝙昙,創(chuàng)建一個(gè)橫屏應(yīng)用烈拒,實(shí)時(shí)預(yù)覽攝像頭圖像,實(shí)現(xiàn)錄像并輸出MP4的功能。
申請(qǐng)權(quán)限
<!-- 需要錄制音視頻權(quán)限和寫(xiě)外部存儲(chǔ)權(quán)限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
在activity中動(dòng)態(tài)申請(qǐng)權(quán)限
private static final String[] VIDEO_PERMISSIONS = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
實(shí)現(xiàn)攝像頭預(yù)覽功能
使用SurfaceView來(lái)預(yù)覽狈涮。新建CameraPreview類繼承自SurfaceView并實(shí)現(xiàn)SurfaceHolder.Callback;
camera相關(guān)操作都放在這個(gè)View里歌馍。
surfaceCreated中獲取Camera實(shí)例握巢,啟動(dòng)預(yù)覽;設(shè)置預(yù)覽相關(guān)參數(shù)
surfaceDestroyed釋放Camera
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static int mOptVideoWidth = 1920; // 默認(rèn)視頻幀寬度
private static int mOptVideoHeight = 1080;
private Uri outputMediaFileUri;
private String outputMediaFileType;
public CameraPreview(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
}
private static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
Log.d(TAG, "camera is not available");
}
return c;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mCamera = getCameraInstance();
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
getCameraOptimalVideoSize(); // 找到最合適的分辨率
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
private void getCameraOptimalVideoSize() {
try {
Camera.Parameters parameters = mCamera.getParameters();
List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
List<Camera.Size> mSupportedVideoSizes = parameters.getSupportedVideoSizes();
Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(mSupportedVideoSizes,
mSupportedPreviewSizes, getWidth(), getHeight());
mOptVideoWidth = optimalSize.width;
mOptVideoHeight = optimalSize.height;
Log.d(TAG, "prepareVideoRecorder: optimalSize:" + mOptVideoWidth + ", " + mOptVideoHeight);
} catch (Exception e) {
Log.e(TAG, "getCameraOptimalVideoSize: ", e);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mHolder.removeCallback(this);
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
}
}
在Fragment中顯示攝像頭預(yù)覽
預(yù)置一個(gè)FrameLayout松却,實(shí)例化一個(gè)CameraPreview添加進(jìn)去
/**
* 視頻錄制界面
* Created by Rust on 2018/5/17.
*/
public class VideoRecordFragment extends Fragment {
private static final String TAG = "rustAppVideoFrag";
private Button mCaptureBtn;
private CameraPreview mCameraPreview;
public static VideoRecordFragment newInstance() {
return new VideoRecordFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "frag onCreate");
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "frag onCreateView");
return inflater.inflate(R.layout.frag_video_record, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "frag onViewCreated");
super.onViewCreated(view, savedInstanceState);
mCaptureBtn = view.findViewById(R.id.capture_btn);
//mCaptureBtn.setOnClickListener(mOnClickListener);// 錄制鍵
mCameraPreview = new CameraPreview(getContext());
FrameLayout preview = view.findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
}
}
使用MediaRecorder錄制
給MediaRecorder指定參數(shù)后暴浦,調(diào)用start()開(kāi)始錄制,stop()結(jié)束錄制
錄制開(kāi)始前晓锻,獲取camera歌焦,mCamera.unlock()解鎖;錄制完畢后砚哆,清除MediaRecorder独撇,mCamera.lock()
private MediaRecorder mMediaRecorder;
public boolean startRecording() {
if (prepareVideoRecorder()) {
mMediaRecorder.start();
return true;
} else {
releaseMediaRecorder();
}
return false;
}
public void stopRecording() {
if (mMediaRecorder != null) {
mMediaRecorder.stop();
}
releaseMediaRecorder();
}
public boolean isRecording() {
return mMediaRecorder != null;
}
private boolean prepareVideoRecorder() {
if (null == mCamera) {
mCamera = getCameraInstance();
}
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mMediaRecorder.setVideoSize(mOptVideoWidth, mOptVideoHeight);
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
mMediaRecorder.setPreviewDisplay(mHolder.getSurface());
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
private void releaseMediaRecorder() {
if (mMediaRecorder != null) {
mMediaRecorder.reset();
mMediaRecorder.release();
mMediaRecorder = null;
mCamera.lock();
}
}
private File getOutputMediaFile(int type) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), TAG);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
outputMediaFileType = "image/*";
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
outputMediaFileType = "video/*";
} else {
return null;
}
outputMediaFileUri = Uri.fromFile(mediaFile);
return mediaFile;
}
后臺(tái)返回時(shí)預(yù)覽黑屏的問(wèn)題
CameraPreview是我們?cè)贔ragment創(chuàng)建時(shí)實(shí)例化并添加進(jìn)去的。
應(yīng)用退到后臺(tái)后躁锁,CameraPreview已經(jīng)被銷(xiāo)毀纷铣。應(yīng)用回到前臺(tái)時(shí),我們應(yīng)該在onResume方法中進(jìn)行操作战转∷蚜ⅲ恢復(fù)CameraPreview盏浇。
在Fragment中坤次,判斷銷(xiāo)毀和重建預(yù)覽的時(shí)機(jī)。
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause: 銷(xiāo)毀預(yù)覽");
mCameraPreview = null;
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume: 回到前臺(tái)");
if (null == mCameraPreview) {
initCameraPreview();
}
}
private void initCameraPreview() {
mCameraPreview = new CameraPreview(getContext());
FrameLayout preview = mRoot.findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
}
相關(guān)代碼請(qǐng)參閱: https://github.com/changhaismile/CameraRecorder