0

I am trying to play audio files on an Android game built with Cordova 6.1.1 and Phaser.io 2.4.6. The media will not play on Android versions less than API 21 or so, and gives the error

04-21 21:48:57.546 9659-9671/com.jtronlabs.birdu E/MediaPlayer: error (1, -2147483648)
04-21 21:48:57.546 9659-9672/com.jtronlabs.birdu E/MediaPlayer: Error (1,-2147483648)

I have read some SO answers, and nothing has helped. I load in audio using Phaser's Loader class:

this.load.audio('background-music', this.arrayOfCompatibleMusicFileNames('the_plucked_bird') ); 

...

//Phaser has support to load in multiple types of audio formats if the first supplied in the array is not compatible with the browser.
arrayOfCompatibleMusicFileNames: function(key){
  //old versions of android don't play music, they require an absolute pathname (instead of relative). This is a generic solution
  //https://stackoverflow.com/questions/4438822/playing-local-sound-in-phonegap?lq=1
  var path = window.location.pathname;
  path = path.substr( 0, path.lastIndexOf("/")+1 ); //need to remove 'index.html' from the end of pathname
  var aud = path+'assets/audio/';

  //aud = '/android_res/raw/'
  var wav = aud + 'wav/';
  var ogg = aud + 'ogg/';
  var mp3 = aud + 'mp3/';

  console.log(mp3+key+".mp3");

  return [mp3+key+".mp3",ogg+key+".ogg",wav+key+".wav"];
},

This works in the browser, and on newer versions of Android. On older versions I have attempted to add multiple formats, the absolute path, external write permissions to $PROJECT_ROOT/platforms/android/AndroidManifest.xml, and moving the files from /www to $PROJECT_ROOT/platforms/android/res/raw.

All for naught. Any ideas on what could be going wrong?

Edit: When the audio files are in the 'res' folder, I reference them as such:

arrayOfCompatibleMusicFileNames: function(key){
  return ['/android_res/raw/'+key+".ogg"];
}

Which works on API 21 but not 19 or below (just like the first function).

Community
  • 1
  • 1
James L.
  • 12,893
  • 4
  • 49
  • 60

1 Answers1

0

I have gotten the Audio working by using the cordova-plugin-media.

var path = window.location.pathname;
path = path.substr( 0, path.lastIndexOf("/")+1 ); //need to remove 'index.html' from the end of pathname
var aud = path+'assets/audio/';

var ogg = aud + 'ogg/' + key + ".ogg";

//works!
var snd = new Media(ogg);
snd.play();

However, I discovered the 'normal' way of doing this is what causes the bad behaviour.

//does not work... Phaser uses this internally
var snd = new Audio(ogg);
snd.play();

It seems I will have to write code to test if it is browser or cordova, and use 'Media' or 'Audio' respectively.

Update: I wrote that code and it makes things messy, but works. Nowadays I use Crosswalk, and WebAudio works on all devices. No need for the media plugin and extra case-checking in my code.

James L.
  • 12,893
  • 4
  • 49
  • 60