I’ve been trying for about 2 weeks now to get sound looping to work, but there seems to be an issue with every method I’ve been able to find. These are the things I’ve tried so far, as well as the issues that I’ve ran into.
- Using the normal
setLooping
function.
val mediaPlayer = MediaPlayer().apply {
setDataSource(file.inputStream().fd)
isLooping = true
setOnPreparedListener {
it.seekTo(0)
it.start()
}
setOnErrorListener { ... }
prepareAsync()
}
This doesn’t work for me because there’s often a delay between loops, causing it to become out of sync with the haptics and the animation that are playing at the same time.
- Interweaving media players and using the
setNextMediaPlayer()
function.
val current: MediaPlayer? = null
val next: MediaPlayer? = null
init {
current = MediaPlayer().apply {
setDataSource(file.inputStream().fd)
setOnPreparedListener {
it.seek(0)
it.start()
}
setOnErrorListener { ... }
prepareAsync()
}
createNextPlayer()
}
fun createNextPlayer() {
next = MediaPlayer.apply() {
setDataSource(file.inputStream().fd)
setOnPreparedListener {
it.seek(0)
current?.let {
it.setNextMediaPlayer(next)
it.setOnCompletionListener {
it?.release()
current = next
createNextPlayer()
}
}
}
}
}
This doesn’t work for me because on some phones (Pixel 6a, Galaxy S22) the onCompletionListener
seems to be called before the sound file is actually completed, causing it to become out of sync with haptics and animation. This method does however work on the Note 9 and Galaxy S7.
- Using
android.media.SoundPool
This doesn’t work for me because the audio files are too big (I can’t make them smaller, they’re compressed as much as possible).
- Using
java.util.Timer
to control when theMediaPlayers
start playing
This seems to work for a bit but gradually becomes more and more out of sync with the animation and haptics. There’s also no way to allow for pausing as far as I can tell, so this isn’t a good solution for my use case.
I know that this issue has been around for a LONG time (2011 is when it was first reported that .isLooping = true
doesn’t seamlessly loop), but I’m hoping someone has a secret technique that I can use. Everything is working perfectly on iOS, and the haptics are looping perfectly on Android, so this is the last thing I have to work on for this particular feature.
Any help is appreciated.