Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Sound In Meteor-Cordova App

Tags:

meteor

cordova

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.

like image 609
Nate Avatar asked Dec 11 '14 21:12

Nate


2 Answers

tl;dr

  1. Install cordova media plugin meteor add cordova:[email protected]

  2. Add audio files to public directory

  3. 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

like image 125
allen Avatar answered Oct 18 '22 17:10

allen


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()
like image 29
Nate Avatar answered Oct 18 '22 17:10

Nate