I’ve developed a simple Android application where you can play and stop audio using MediaPlayer
. However the audio doesn’t stop when requested to.
Here is a breakdown of the app. There are two buttons in a column. The first button prepares and plays an audio file. The second stops playing the audio file.
Here is the code for the MainActivity
// Sound Effect Uri
val soundEffectUri = "android.resource://com.example.audiotest/raw/sound_effect"
// App Layout
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
// Button That Plays Audio
Button(onClick = { AudioClass(this).play() })
{ Text(text = "Start") }
// Button That Stops Audio
Button(onClick = { AudioClass(this).stop() })
{ Text(text = "Stop") }
The logic for the MediaPlayer
is kept in a seperate class. Here it is
// Class That Holds MediaPlay Logic
class AudioClass(context: Context) {
// Instance Of MediaPlayer
val mediaPlayer = MediaPlayer()
// MediaPlayer Attributes
init {
mediaPlayer.setDataSource(context, Uri.parse(soundEffectUri))
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM)
mediaPlayer.isLooping = true
}
// Function That Prepares And Starts Audio
fun play() {
mediaPlayer.prepare()
mediaPlayer.start()
}
// Function That Stops Audio
fun stop() {
mediaPlayer.stop()
}
}
The problem of audio not stopping only occurs when the MediaPlayer
is initialized outside of an Activity
or Composable
. I’d like to initialize it globally so that I can use it where ever it’s needed.
Here is what the log cat says whenever I press the button that stops the audio.
2024-09-23 19:10:55.088 22661-22661 MediaPlayerNative com.example.audiotest E stop called in state 2, mPlayer(0xd25cb1e0)
2024-09-23 19:10:55.088 22661-22661 MediaPlayerNative com.example.audiotest E error (-38, 0)
2024-09-23 19:10:55.149 22661-22661 MediaPlayer com.example.audiotest E Error (-38,0)
Thanks for taking your time to read this question.
2
Answers
The states of MediaPlayer are:
1 Idle
2 Initialized
3 Preparing
4 Prepared
5 Started
6 Paused
7 Stopped
8 PlaybackCompleted
9 End
10 Error
The Stop operation can’t be called when the state is 2(Initialized).
It can only be called when the MediaPlayer is in the Started, Paused, or PlaybackCompleted states
Check it based on the above logic.
Looks like you are staring and stopping 2 different players.
You should create and remember only one instance.