Reputation: 1160
This is my code snippet.
private fun record() {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
val path: File = filesDir
try {
tempFile = File.createTempFile("audioTemp", ".3gp", path)
} catch (e: IOException) {
Log.d("recording error", "recording error:", e)
} catch (e: FileAlreadyExistsException) {
Log.d("File already Exist", e.toString())
}
recorder.setOutputFile(tempFile?.absolutePath)
try {
recorder.prepare()
} catch (e: IOException) {
Log.d("recording error", "recording error:", e)
}
recorder.start()
}
private fun stopRecord() {
recorder.stop()
recorder.release()
button_play_sample.isEnabled = true
button_record.isEnabled = true
player.setOnCompletionListener(this)
try {
player.setDataSource(tempFile?.absolutePath)
} catch (e: IOException) {
Log.d("stop recording error", "Stop Recording Error:", e)
}
try {
player.prepare()
} catch (e: IOException) {
Log.d("recording error", "recording error:", e)
}
}
private fun play() {
player.start()
button_record.isEnabled = false
}
override fun onCompletion(mp: MediaPlayer?) {
handler = Handler()
handler?.postDelayed({button_record.isEnabled = true}, 1000)
}
I cant figure out why but I have a record button that records audio. When the activity first loads, the recording loads. When I press it the second time because I don't like my first recording, instead of overwriting the old file and setting up record again, App crashes instead.
Upvotes: 2
Views: 204
Reputation: 1789
In the Android Developer Guide, it says
When you are done with the MediaRecorder instance free its resources as soon as possible by calling release().
see this sample code from the Developer site:
private void stopRecording() {
recorder.stop();
recorder.release();
recorder = null;
}
Your code snippet doesn't check if recorder
is being used. You might want to do that before using the MediaRecorder
object again.
private fun record() {
if (recording) {
stopRecording()
}
// do recording snippet here...
}
Upvotes: 3