Using native MediaRecorder API to implement recording function in Android

1. Introduction to MediaRecorder

MediaRecorder is an API in Android that can be used to implement the recording function. It inherits from the android.media.MediaRecorder class and can achieve audio and video recording.

2. Use of MediaRecorder

1. First, instantiate a MediaRecorder object and set the audio source:

val recorder = MediaRecorder()
recorder.setAudioSource(MediaRecorder.AudioSource.MIC)

2. Set the audio output format:

recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)

3. Set the audio encoding format:

recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)

4. Set the path of the recording file:

var path=""

var fileName = "${DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA))}.m4a"

var audioSaveDir=filesDir.absolutePath

path="$audioSaveDir$fileName"
recorder.setOutputFile(path);

5. Prepare to record:

recorder.prepare()

6. Start recording:

recorder.start()

7. Stop recording:

recorder.stop()

8. Release resources:

recorder.release()

3. Advantages and Disadvantages of MediaRecorder

MediaRecorder can record audio and video, can set different output formats, can set different encoding formats, can also set different volumes, can set different recording file paths, and so on.

However, MediaRecorder also has some shortcomings, such as it can only record audio and video, but not images; the implementation steps are not simple enough, the path of the recording file also needs to be set in advance and cannot be set dynamically, and its recording effect is not very good.

Guess you like

Origin blog.csdn.net/jsonCheng/article/details/131191908