Twitter: raymondcamden


Address: Lafayette, LA, USA

Cordova Media API Example

06-23-2014 7,557 views Mobile, JavaScript, HTML5

A few months ago I launched a new GitHub repo (https://github.com/cfjedimaster/Cordova-Examples) as a way to try to collect my various Cordova examples together under one roof. I had planned to add to it regularly but - life - as you know - gets in the way. I've finally gotten around to adding another example, this one for the Media API.

Specifically, my example looks at how to play a MP3 file that is shipped with your application. You would think this would be trivial. Assuming I've got a folder under www called sounds and a MP3 file called something.mp3, you would think this would do it:

var media = new Media("sounds/something.mp3", null, mediaError);
media.play();

Unfortunately, this breaks in Android. Why? Because Android. (No, no, I kid, sorry.) Specifically Android requires slightly different "pathing" to get to the same source. Specifically it requires this in front of the path: /android_asset/www/

So what I did was write a simple utility function that makes use of the Device API. Consider:

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
	document.querySelector("#playMp3").addEventListener("touchend", playMP3, false);
};

function playMP3() {
    var mp3URL = getMediaURL("sounds/button-1.mp3");
    var media = new Media(mp3URL, null, mediaError);
    media.play();
}

function getMediaURL(s) {
    if(device.platform.toLowerCase() === "android") return "/android_asset/www/" + s;
    return s;
}

function mediaError(e) {
    alert('Media Error');
    alert(JSON.stringify(e));
}

All I've done is sniff for the Android platform and modify the passed-in path value to add the Android prefix. I did not test this outside of iOS and Android so I can't say if it will work in Blackberry or Firefox, but, it gives you a basic idea of how to use a MP3 in your application.

You can find the source for this particular project here: https://github.com/cfjedimaster/Cordova-Examples/tree/master/mp3. As a reminder, you can clone the entire repository, and when you make a new Cordova project, simply use the --copy-from attribute to copy in my source code.