I'm using libgdx to play some background music for a game I'm writing. I have an array of potential music to be played, and I would like that when the current song finishes, another one is chosen at random from the array.
The problem I'm having is working out when the Music is finished.
The Music class doesn't appear to have any event handlers I could attach to, nor does it have a way of telling me how long it'll take for particular music to finish.
The only idea which comes to mind involves polling
music.isPlaying()
On a loop of some sort, to be able to determine when its stopped. But this is an ugly solution in my opinion - and won't work if (say) the user has turned sound off.
Is there anything else I could do ?
In the latest versions of LibGDX you can define a OnCompletetionListener
for your Music
. See the documentation. It will be called when the current playback of your music reached the end.
When using Sound
there is a known problem about this feature. With Sound there really is no way to know when it finished, thanks to the Android API which needs to be supported. I'd suggest the gdx-audio extension in this case, but it's much more low-level and not available for GWT/iOS. See the wiki.