From 2cc99495703a4a73983796ff5dd03d06e586f608 Mon Sep 17 00:00:00 2001 From: xufuji456 Date: Tue, 22 Mar 2022 21:51:17 +0800 Subject: [PATCH] Feature: add MediaRecordController --- .../controller/MediaRecordController.kt | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 AndroidMedia/src/main/java/com/frank/androidmedia/controller/MediaRecordController.kt diff --git a/AndroidMedia/src/main/java/com/frank/androidmedia/controller/MediaRecordController.kt b/AndroidMedia/src/main/java/com/frank/androidmedia/controller/MediaRecordController.kt new file mode 100644 index 0000000..e61a21f --- /dev/null +++ b/AndroidMedia/src/main/java/com/frank/androidmedia/controller/MediaRecordController.kt @@ -0,0 +1,71 @@ +package com.frank.androidmedia.controller + +import android.hardware.Camera +import android.media.CamcorderProfile +import android.media.MediaRecorder +import android.util.Log +import android.view.Surface + +/** + * Using MediaRecorder to record a media file. + * + * @author frank + * @date 2022/3/21 + */ +open class MediaRecordController { + + private var mCamera: Camera? = null + private var mMediaRecorder: MediaRecorder? = null + + private fun initMediaRecord(surface: Surface, outputPath: String) { + // open camera + mCamera = Camera.open() + mCamera!!.setDisplayOrientation(90) + mCamera!!.unlock() + // Note: pay attention to calling order + mMediaRecorder?.setCamera(mCamera) + mMediaRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC) + mMediaRecorder?.setVideoSource(MediaRecorder.VideoSource.CAMERA) + mMediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) + mMediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC) + mMediaRecorder?.setVideoEncoder(MediaRecorder.VideoEncoder.H264) + mMediaRecorder?.setOutputFile(outputPath) + mMediaRecorder?.setPreviewDisplay(surface) + } + + fun startRecord(surface: Surface, outputPath: String) { + if (mMediaRecorder == null) { + mMediaRecorder = MediaRecorder() + } + + initMediaRecord(surface, outputPath) + + try { + mMediaRecorder?.prepare() + mMediaRecorder?.start() + } catch (e: Exception) { + Log.e("MediaRecorder", "start recorder error=$e") + } + Log.i("MediaRecorder", "startRecord...") + } + + fun stopRecord() { + if (mMediaRecorder != null) { + mMediaRecorder?.stop() + mMediaRecorder?.reset() + } + mCamera?.stopPreview() + Log.i("MediaRecorder", "stopRecord...") + } + + fun release() { + if (mMediaRecorder != null) { + mMediaRecorder?.release() + mMediaRecorder = null + } + if (mCamera != null) { + mCamera!!.release() + mCamera!!.lock() + } + } +} \ No newline at end of file