6

It works fine on iOS.

I have looked many answers including these 2:

Play sound on Phonegap app for Android

HTML5 audio not playing in PhoneGap App (Possible to use Media?)

I have tried all of the solutions:

  • Changing the path to /android_asset/www/ for Android
  • Using .ogg files
  • Pre load the audio with a play() / pause().
  • Using the Media plugin provided by Cordova/Phonegap

Here is my current code:

if(device.platform === "Android")   //DIFFERENT PATH FOR ANDROID
{
    url = "/android_asset/www/sound.ogg";
}else{
    url = "sound.mp3";
}
alert(url);
sound = new Media(url);
sound.play();

Anyone have an ideas?? It feels like I have been going round in circles

smj2393
  • 1,929
  • 1
  • 23
  • 50

2 Answers2

2

I had similar and this solution worked for me Get complete path of your application using window.location.pathname, this way you dont need to worry about device type, it will give you the complete path including index.html and by using the below function simply strip off index.html from the string and append your media file.

function getPhoneGapPath() {

var path = window.location.pathname;
path = path.substr( path, path.length - 10 ); //strip off index.html
return 'file://' + path;

};

And then

url = getPhoneGapPath()+'sound.ogg';  //OR MP3 

alert(url);
sound = new Media(url);
sound.play();

Hope this helps

Sarim Sidd
  • 2,166
  • 2
  • 22
  • 31
0

I finally managed to get it working!!

I first initialising the audio file by finding the full Android path using @Sarim Sidd help above and then preloading the audio file:

//INITIALISE SOUND
if(device.platform === "Android")   //DIFFERENT PATH FOR ANDROID
{
    //navigator.notification.beep(1);
    var path = window.location.pathname;
    path = path.substr( path, path.length - 10 ); //strip off index.html
    url = 'file://'+path+"sound.ogg";
}else{
    url = "sound.mp3";
}
//sound = new Media(url);
sound = new Media(url);
sound.play();
sound.pause();

Then when to play the audio I forced the volume to full (1.0) before calling the play method. For some reason I noticed the audio kept reseting to mute each time I started the app:

//PLAY BELL SOUND THROUGH APP
sound.setVolume(1.0);
sound.play();
smj2393
  • 1,929
  • 1
  • 23
  • 50