I am creating a Screen recording app and using MediaRecorder for recording video. The screen recording works fine when I set the audio source for media recorder instance through setAudioSource(...)
. Since this approach also lets me record audio along with video, I also want to record video without audio. So, for that i removed the setAudioSource(...)
function call (as stated by the documentation):-
Sets the audio source to be used for recording. If this method is not called, the output file will not contain an audio track.
Code:-
private fun createMediaRecorder(mScreenWidth: Int, mScreenHeight: Int): MediaRecorder {
val mMediaRecorder = MediaRecorder()
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT) //code doesn't work without this line of code
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE)
val profile: CamcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)
profile.videoFrameWidth = mScreenWidth
profile.videoFrameHeight = mScreenHeight
mMediaRecorder.setProfile(profile)
setOutputFile(mMediaRecorder)
mMediaRecorder.prepare()
return mMediaRecorder
}
private fun setOutputFile(mediaRecorder: MediaRecorder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val contentVals = ContentValues()
contentVals.put(MediaStore.MediaColumns.DISPLAY_NAME, "some")
contentVals.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4")
contentVals.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_MOVIES)
val uri =
contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentVals)
val fileDescriptor = contentResolver.openFileDescriptor(uri!!, "w")
mediaRecorder.setOutputFile(fileDescriptor!!.fileDescriptor)
} else {
val fileDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
val file = File(fileDir, "some.mp4")
mediaRecorder.setOutputFile(file.path)
}
}
Exception:-
Caused by: java.lang.IllegalStateException
at android.media.MediaRecorder.setAudioEncoder(Native Method)
at android.media.MediaRecorder.setProfile(MediaRecorder.java:559)
at com.abdulwahabfaiz.myapplication.MediaService.createMediaRecorder(MediaService.kt:120)
at com.abdulwahabfaiz.myapplication.MediaService.onStartCommand(MediaService.kt:56)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…