Using meteor without cordova I can play a sound fine in my browser using
new Audio('test.mp3').play()
where test.mp3
is located in the public folder. However I cannot play the sound once I run my app as a cordova app on a device. What am I doing wrong? Thanks.
tl;dr
Install cordova media plugin meteor add cordova:[email protected]
Add audio files to public directory
Use /android_asset/www/application/path/to/sound.wav
If you look inside this folder in your project,
$PROJECT_ROOT/.meteor/local/cordova-build/platforms/android/assets/www/
You will see your application as cordova built it for android.
Using the Cordova Media plugin, I attempted to use the file path /android_asset/www/path/to/sound.wav
to no avail.
# Install the cordova media plugin with this command
meteor add cordova:[email protected]
Instead, I saw that my sounds folder was inside the www directory but under an application directory. So, this file path ended up working for me,
/android_asset/www/application/path/to/sound.wav
Here's the relevant code that worked for me.
function getMediaUrl(sound) {
if (device.platform.toLowerCase() === "android") {
return cordova.file.applicationDirectory.replace('file://', '') + 'www/application/' + sound.substr(1);
}
else {
return cordova.file.applicationDirectory.replace('file://', '') + sound.substr(1);
}
}
function playSound(sound) {
return new Media(
getMediaUrl(sound),
function (success) {
// success
},
function (err) {
// error
}
);
}
var test = playSound('/sounds/test.wav');
test.play();
NOTE: I included my audio files in the public folder i.e.
$PROJECT_ROOT/public/sounds/test.wav
and on Android, this file path is translated to
/android_asset/www/application/sounds/test.wav
There seems to be two possible solutions. The first which is probably the more correct solution is only valid for cordova apps. It will not work in the browser due to the plugin dependency. First step is to add the cordova plugin:
meteor add cordova:[email protected]
Next build a function to play the sound:
playLimitSound = function() {
if (Meteor.isCordova) {
var my_media = new Media('http://MY_IP:port/test.mp3',
// success callback
function () {
console.log("playAudio():Audio Success");
},
// error callback
function (err) {
console.log("playAudio():Audio Error: " + err);
}
);
// Play audio
my_media.play();
}
};
This is another solution. It works both in browser and cordova-app.
new Audio('http://MY_IP:port/test.mp3').play()
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