I'm developing an application with phonegap, and I have a sound file I want to play that's in a path like so www/Sounds/sound.mp3, and I'm trying to access this file using the Media object of Phonegap in order to play it.
I cannot figure out the path to access this sound file within a javascript file that uses the Media object? I've tried paths like, file:///www/Sounds/sound.mp3, relative paths, etc and I cannot access it. I keep getting the following error in xcode 4
Will attempt to use file resource 'file:///www/Sounds/sound.mp3'
Unknown resource 'file:///www/Sounds/sound.mp3'
What path do I need to use to access the file? Or do I need to copy the sound file out of my www directory and into my Resources folder and access it there?
My WWW folder is referenced, not sure if that makes a difference.
Heres a modified version of getPhoneGapPath that works for me on both iOS and Android. It is also not restricted to only working on files that have a filename that is 10 characters long :)
getPhoneGapPath: function () {
'use strict';
var path = window.location.pathname;
var phoneGapPath = path.substring(0, path.lastIndexOf('/') + 1);
return phoneGapPath;
}
var resource = getPhoneGapPath() + 'audio/audio.mp3';
getPhoneGapPath() will return:
iOS: /var/mobile/Applications/{GUID}/{appName}/www/
Android: /android_asset/www/
Use window.location.pathname
to get the path of your application. It will look something like this on iPhone:
/var/mobile/Applications/{GUID}/{appname}.app/www/index.html
And this on Android:
/android_asset/www/index.html
Strip off the /index.html
, prepend file://
, and append your relative path Sounds/sound.mp3
.
Here's something to get you started:
Demo: http://jsfiddle.net/ThinkingStiff/chNVY/
Code:
function getPhoneGapPath() {
var path = window.location.pathname;
path = path.substr( 0, path.length - 10 );
return 'file://' + path;
};
var resource = getPhoneGapPath() + 'Sounds/sound.mps';
The best answer is outdated. You are now able to play wav
, mp3
, and caf
formats on iOS using this "relative path" method:
var media = new Media('beep.wav', ...);
Note that the above code requires the sound file to be in the root of your www/
directory -- in this example at www/beep.wav
. If you want to put them in a subdiretory like www/sounds/
, you'll need to specify it using a path relative to your www/
directory. For example, this also works now:
var media = new Media('sounds/beep.wav', ...);
for the sound file at www/sounds/beep.wav
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With