Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Music stops playing after some time by using MediaPlayer class

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.

I tried to solve but I can’t find solution kindly tell me how to solve this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading