Kozuch
Kozuch

Reputation: 2292

PhoneGap on iOS: play new media before currently playing one ends

I have a simple JavaScript game built on PhoneGap (Cordova), where user is looking for certain features in a picture. After a correct feature if found, an audio (jingle notifying of correct answer) is played. Though I have a problem - the jingle is X seconds long. When the user finds another correct feature before the previous jingle finished playing (time is smaller than X), the new jingle will not start playing. I need every new jingle to override the previous one in case the previous one has not finished playing yet (and so let the user acoustically the last correct feature guess).

Here is my code - it working like I want on Android:

var gMedia;

function playAudio(src, callback) {

    if (gMedia) { 
        gMedia.stop();
        gMedia.release();
    }

    var mediaSource;
    if (iOS) mediaSource = "sounds/" + src;
    else mediaSource = "/android_asset/www/sounds/" + src;

    gMedia = new Media(mediaSource, onSuccess, onError);
    gMedia.play();
    gMedia.setVolume('1.0');    

    // onSuccess Callback
    function onSuccess() {
        gMedia.release();
        if (callback && typeof(callback) === "function") {
            callback.call();
        }
    }

    // onError Callback 
    function onError(error) {
        gMedia.release();
    }
}

Upvotes: 0

Views: 631

Answers (1)

jonas
jonas

Reputation: 935

It seems, the problem is that you release the Media object in your success callback because it will also be called when you stop the sound (gMedia.stop()). So when you create the new Media object it will be released right away.

In the tests I've made your code works fine after removing the gMedia.release() from your onSuccess function.

Upvotes: 1

Related Questions