问题
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
回答1:
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
回答2:
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();
来源:https://stackoverflow.com/questions/30259395/audio-will-not-play-on-android-using-phonegap-but-works-fine-on-ios