How to use android MediaPlayer class to play a sound in a loop

I’m making a metronome app. This means I need to play a sound in a loop for a few times and then every some number of times play another sound. My first approach to playing a sound in a loop is as follows:

fun startMetronome(){
    isPlaying = true
    upbeat = MediaPlayer.create(this, R.raw.upbeat)
    CoroutineScope(Dispatchers.IO).launch {
        while(isPlaying) {
            for(i in 0..5){continue}
                upbeat?.start()
                Thread.sleep(500)
        }
    }
}

The problem is this causes the loop to randomly hang every few ticks. The solution to that would be to move the assignment of the upbeat variable:

fun startMetronome(){
    isPlaying = true
    CoroutineScope(Dispatchers.IO).launch {
        while(isPlaying) {
            for(i in 0..5){continue}
                //moved it here
                upbeat = MediaPlayer.create(this, R.raw.upbeat)
                upbeat?.start()
                Thread.sleep(500)
        }
    }
}

but that on the other hand throws an error when the loop is in a CoroutineScope, which I need beacause I want to be able to play and stop the loop. If any of you know the correct way to do it please let me know.

Leave a Comment