I am using below approach for playing music on a button click in android app.
val mediaPlayer = MediaPlayer.create(this, R.raw.game_jump)
mediaPlayer.start()
Initially music is playing by clicking on button but after clicking few times on button, music stops playing.
How to solve this?
CodePudding user response:
When you create an instance of MediaPlayer class, the system allocates resources (including memory) to load and play the media file. If you don't release these resources properly, it can lead to issues like high memory consumption, memory leaks, and even the application crashing due to resource exhaustion.
To solve the issue you should release the resources of the MediaPlayer instance, by calling the release() method, once you are done using it.
val mediaPlayer = MediaPlayer.create(this, R.raw.sound)
mediaPlayer.start()
mediaPlayer.setOnCompletionListener {
mediaPlayer.release()
}
But using MediaPlayer class for shorter sound tracks (for example playing sound on button click in your case) is not recommended because it may consume more memory and processing resources. it is suitable for scenarios where you need to play longer audio files, such as music tracks or longer sound effects.
for shorter sound tracks you can use SoundPool. The SoundPool class is designed specifically for playing short sound effects efficiently such as in games or interactive applications. Here's how you can use that:
val mySoundPool = SoundPool(1, AudioManager.STREAM_MUSIC, 0)
val soundId = mySoundPool.load(this, R.raw.sound, 1)
mySoundPool.setOnLoadCompleteListener { soundPool, _, _ ->
soundPool.play(soundId, 1f, 1f, 1, 0, 1f)
}