Correct Way to Use Media Object in Phonegap

Media object is the default PhoneGap API for playing audio files. But if you are frequently changing/playing the audio tracks in your application using Media, you may end up in some uncommon behaviours like audio stops playing. The console will show some error like 'Cant create audio track..'. Here is the right way to use Media object in PhoneGap.


var media = null;   //Global variable for media object

function playMedia(src) {
    /**
     * Important: Always release media object before reusing it
     */
    if (media != null) {
        media.release();
    }
    media = new Media(src, onMediaSuccess, onMediaError);
    media.play();
}

//success callback
function onMediaSuccess() {
    console.log("Media success.");
}

//error callback
function onError(error) {
    console.log('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}

We would love to hear from you...

back to top