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 = new Media(src, onMediaSuccess, onMediaError);;

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

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

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.