Reputation: 1783
There are already several questions on this topic, but I couldn't get the answer that I want.
So, I would try to provide my minimal test case here, in that case it might help others in the future.
The basic UI look as above, to reproduce the test case, firstly, we should put a MP3 file into local directory, named it as recording1.mp3
.
Then click the PLAY button to play the recording1.mp3
, when the mp3 is playing, click START button to start recording and click STOP to finish recording.
The core logic would looks like:
button_start_recording.setOnClickListener {
if (ContextCompat.checkSelfPermission
...
} else {
mediaRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC)
mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
mediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
mediaRecorder?.setOutputFile(output)
startRecording()
}
}
private fun startRecording() {
try {
mediaRecorder?.prepare()
mediaRecorder?.start()
state = true
Toast.makeText(this, "Recording started!", Toast.LENGTH_SHORT).show()
} catch (e: IllegalStateException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun startPlaying() {
try {
thread {
val playSource =
Environment.getExternalStorageDirectory().absolutePath + "/recording1.mp3"
mediaPlayer?.setDataSource(playSource)
mediaPlayer?.prepare()
mediaPlayer?.start()
}
} catch (e: IllegalStateException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
I wanna get the record that would mix the background music as the recording1.mp3
was playing and the audio was recorded. But what I got was only the recording1.mp3
sound.
Upvotes: 0
Views: 814
Reputation: 36
I Think,change your mediaRecorder?.setoutFormat
to
mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS)
Or
mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
prepare your MediaPlayer mediaPlayer?.prepare()
before starting of your recording
And, play your Background music (with volume as you want) and start the recorder .
May it Works. Thanks!
Upvotes: 2