Looping Audio with PhoneGap

Playing media on repeat

Playing media is easy with Phonegap / Cordova using the core media plugin. I’m using it in the game I’m writing.

The issue is, I wanted to be able to play a background music loop on repeat (don’t worry, the user can switch this off in my apps settings, or simply mute the sound).

iOS

There’s an “iOS Quirk” that makes this really easy for iOS devices. From the documentation:

numberOfLoops: Pass this option to the play method to specify the number of times you want the media file to play”
1
2
var myMedia = new Media("/audio/my.mp3");
myMedia.play({ numberOfLoops: 2 });

It’s a bit frustrating that you can’t do numberOfLoops: -1 to repeat indefinitely, but I can live with it. The issue is, you can’t do this on Android.

Android

Here’s my work around (that I also for iOS too to keep the JavaScript consistent). It’s really frustrating because this could easily be built into the plugin’s native component.

1
2
3
4
5
6
7
8
9
10
var myMedia;
var loop = function (status) {
if (status === Media.MEDIA_STOPPED) {
myMedia.play();
}
};
myMedia = new Media("/audio/my.mp3", null, null, loop);
myMedia.play();

I’m using the mediaStatus callback that executes when the media status changes, to check to see if the media has stopped playing (it’s finished) and to play the media again.

Can we have a repeat: true please?