Tuan

Phaser HTML5 app cannot play sound after porting by Phonegap Cloud Build

Recommended Posts

Sorry for an old topic. But I've tried to search but have no luck.

 

This's a simple Phaser audio example. It works well on my Android web browser. However, it's muted after porting to Android app by Phonegap cloud build. Although the app can display and touch.

 

Is there anyone can port Phaser game to Android by Phonegap Cloud Build and it can play audio?

 

Here's my answer on SO but I think it's better to raise it here.

http://stackoverflow.com/questions/33949879/phaser-html5-app-cannot-play-sound-after-porting-by-phonegap-cloud-build

var game = new Phaser.Game(600, 800, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });function preload() {	game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;        //have the game centered horizontally    game.scale.pageAlignHorizontally = true;    game.scale.pageAlignVertically = true;    game.stage.backgroundColor = '#414040';    game.load.audio('explosion', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/explosion.mp3');    game.load.audio('sword', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/sword.mp3');    game.load.audio('blaster', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/blaster.mp3');}var explosion;var sword;var blaster;var text;var text1;var text2;var text3;function create() {    var style = { font: "65px Arial", fill: "#52bace", align: "center" };    text = game.add.text(game.world.centerX, 100, "decoding", style);    text.anchor.set(0.5);    explosion = game.add.audio('explosion');    sword = game.add.audio('sword');    blaster = game.add.audio('blaster');    //  Being mp3 files these take time to decode, so we can't play them instantly    //  Using setDecodedCallback we can be notified when they're ALL ready for use.    //  The audio files could decode in ANY order, we can never be sure which it'll be.    game.sound.setDecodedCallback([ explosion, sword, blaster ], start, this);}var keys;function start() {    text.text = 'Press 1, 2 or 3';    var style = { font: "48px Arial", fill: "#cdba52", align: "center" };    text1 = game.add.text(game.world.centerX, 250, "Blaster: Stopped", style);    text1.anchor.set(0.5);    text2 = game.add.text(game.world.centerX, 350, "Explosion: Stopped", style);    text2.anchor.set(0.5);    text3 = game.add.text(game.world.centerX, 450, "Sword: Stopped", style);    text3.anchor.set(0.5);    explosion.onStop.add(soundStopped, this);    sword.onStop.add(soundStopped, this);    blaster.onStop.add(soundStopped, this);    keys = game.input.keyboard.addKeys({ blaster: Phaser.Keyboard.ONE, explosion: Phaser.Keyboard.TWO, sword: Phaser.Keyboard.THREE });    keys.blaster.onDown.add(playFx, this);    keys.explosion.onDown.add(playFx, this);    keys.sword.onDown.add(playFx, this);    //  And for touch devices you can also press the top, middle or bottom of the screen    game.input.onDown.add(onTouch, this);}function onTouch(pointer) {    var b = game.height / 3;    if (pointer.y <     {        playFx(keys.blaster);    }    else if (pointer.y > b * 2)    {        playFx(keys.sword);    }    else    {        playFx(keys.explosion);    }}function playFx(key) {    switch (key.keyCode)    {        case Phaser.Keyboard.ONE:            text1.text = "Blaster: Playing";            blaster.play();            break;        case Phaser.Keyboard.TWO:            text2.text = "Explosion: Playing";            explosion.play();            break;        case Phaser.Keyboard.THREE:            text3.text = "Sword: Playing";            sword.play();            break;    }}function soundStopped(sound) {    if (sound === blaster)    {        text1.text = "Blaster: Complete";    }    else if (sound === explosion)    {        text2.text = "Explosion: Complete";    }    else if (sound === sword)    {        text3.text = "Sword: Complete";    }}

Share this post


Link to post
Share on other sites

Hi, 

 

check if it's not an issue with content Security Policy. By default PhoneGap (or Cordava) projects start with something like that:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

You have to add your urls in these tag. 

Share this post


Link to post
Share on other sites

ok. official doc contains a warning, not sure if you're in this case: 

Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. The solution is to use a lower encoding rate such as 44100 Hz.

 

Also, can you wait until sounds are decoded (with method onDecoded on each sound)? May be sound is not yet decoded. 

Share this post


Link to post
Share on other sites

Hi Gob0,

 

I don't have Apple device. I'm using Samsung phone.

 

- I put the game to my web server and can play it by my native Android web browser (4.4.4) => my Android phone can decode the sound (.mp3).

- I ported the game to Android app by Phonegap cloud build. It is played but without sound.

 

I tried the Cocoon.io build with the Webview+ mode. The app plays well with sound. But the file size is > 21MB (while the Phonegap is 400kb). :o

 

Maybe I have to edit the preload function.

 

From

game.load.audio('explosion', 'assets/audio/SoundEffects/explosion.mp3');game.load.audio('sword', 'assets/audio/SoundEffects/sword.mp3');game.load.audio('blaster', 'assets/audio/SoundEffects/blaster.mp3');

To

var explosion = new Media('/android_asset/www/assets/audio/SoundEffects/explosion.mp3');var sword= new Media('/android_asset/www/assets/audio/SoundEffects/sword.mp3');var blaster= new Media('/android_asset/www/assets/audio/SoundEffects/blaster.mp3');

I'll update you the result. Thank you for your help! :)

Share this post


Link to post
Share on other sites

I don't think it's a good idea to use android path to load files. This path won't exist when build for iOs or WinPhone.

 

You can check if your audio files are bundled in APK (unsigned): rename the .apk file to .zip and search for files.

Share this post


Link to post
Share on other sites

Hi @Gob0,

 

Phaser plays sound well on web browser. But if you have a Phaser game and you porting it to Android by Phonegap cloud, it can't play sound. :wacko:

If you have any Phaser game and it has sounds, please try to port it to Android app by Phonegap and you will see.

 

I don't use (or don't know how to use) any Cordova media plugin. :( Just let you know that I can make my app play sound if I add another Javascripts outside the Phaser. It works but doesn't have any value to my Phaser game.

 

Example, adding the script into index.html. It can play sound after porting to Android app by Phonegap.

<!DOCTYPE html><html><head>  <title>Phaser game</title>  <meta charset="UTF-8" />  <meta name="viewport" content="initial-scale=1 maximum-scale=1 user-scalable=0 minimal-ui" />  <script src="js/phaser.min244.js" type="text/javascript"></script>  <script src="js/game.js" type="text/javascript"></script>  <script type="text/javascript" charset="utf-8" src="cordova.js"></script>  <script type="text/javascript" charset="utf-8">        document.addEventListener("deviceready", onDeviceReady, false);                //This function is used to specify an absolute path of an mp3 file to be played in a project on Android.        function getPath() {            var str = location.pathname;            var i = str.lastIndexOf('/');            return str.substring(0,i+1);        }                function onDeviceReady() {            //window.alert("Loading PhoneGap is completed");			playAudio('assets/sound.mp3');        }        var media = null;        var mediaTimer = null;        function playAudio(src) {            media = new Media (getPath() + src , onSuccess, onError, onStatus);            media.play();            if (mediaTimer == null) {                mediaTimer = setInterval(function() {                    // Return a current playback position                    media.getCurrentPosition(                        //A Callback function if it's success                        function(position) {                            if (position > -1) {                                setAudioPosition((position) + " sec");                                                                                     //If the playback stops at "-0.001" position, replay the audio.                                       // if(position == -0.001){                                        //    media.play({numberOfLoops:"infinite"});                                                    //}                            }                        },                        //A callback function in case of failure                        function(e) {                            //console.log("Error getting pos=" + e);                            //setAudioPosition("Error: " + e);                        }                    );                }, 1000);            }        }        function pauseAudio() {            if (media) {                media.pause();            }        }        function stopAudio() {            if (media) {                media.stop();            }            clearInterval(mediaTimer);            mediaTimer = null;        }          //A success callback function displaying a success message.          function onSuccess() {              //console.log("playAudio():Audio Success");          }          //A callback function in case of failure          function onError(error) {              //alert('code: '    + error.code    + '\n' +               //      'message: ' + error.message + '\n');          }          //Set the position of audio playback          function setAudioPosition(position) {              document.getElementById('audio_position').innerHTML = position;          }		  		  // onStatus Callback 		  function onStatus(status) {			if( status==Media.MEDIA_STOPPED ) {            playAudio('assets/sound.mp3');			}		 } </script></head><body>  <div id="game-id"></div></body></html>

Share this post


Link to post
Share on other sites

Hi all,

 

This is my first coment in this community. Its two weeks since I started with Phaser. I am a senior engineer who programmed in PASCAL, C++, and Visual Basic in the past. Now I am interested in videogame developing as a hobby.

 

In this two weeks I have got good results from a hard work, and a great surprise about Phaser's powerfull learning curve. In fact I have made a scratch game, loaded it on local an remote servers, and checked it worked OK. 

 

As you mention, the problem appears when I try to migrate it to an .apk file using Intel XDK in my case, (I haven't tried Phonegap). My great dissapointment was the lack of sound. I have tried with XDK media plugins, I have tried using nativeaudio cordova plugin (which I can not manage to get any result). I install this plugin, but after have reviewed some code examples, and I can`t make them work, even the simplest fact of playing a single sound.

 

I think it would be useful, if someone can show a simple script with comments, on just how to play a single track or sound using cordova plugin, detailing how to invoke cordova and how to locate the different plugin scripts in the project folders.

 

I'll keep trying and give some feedback if I succeed

Share this post


Link to post
Share on other sites

Hi all,

 

This is my first coment in this community. Its two weeks since I started with Phaser. I am a senior engineer who programmed in PASCAL, C++, and Visual Basic in the past. Now I am interested in videogame developing as a hobby.

 

In this two weeks I have got good results from a hard work, and a great surprise about Phaser's powerfull learning curve. In fact I have made a scratch game, loaded it on local an remote servers, and checked it worked OK. 

 

As you mention, the problem appears when I try to migrate it to an .apk file using Intel XDK in my case, (I haven't tried Phonegap). My great dissapointment was the lack of sound. I have tried with XDK media plugins, I have tried using nativeaudio cordova plugin (which I can not manage to get any result). I install this plugin, but after have reviewed some code examples, and I can`t make them work, even the simplest fact of playing a single sound.

 

I think it would be useful, if someone can show a simple script with comments, on just how to play a single track or sound using cordova plugin, detailing how to invoke cordova and how to locate the different plugin scripts in the project folders.

 

I'll keep trying and give some feedback if I succeed

 

I understand yours. I made some games by Phaser and was very happy. But they can't play sound after porting to .apk by Phonegap.

You can try cocoon.io (WebView+ mode), it can play sound but the file size is big (> 20MB).

Share this post


Link to post
Share on other sites

Thanks Tuan

 

I hope to review some of the examples in Intel XDK, using both media and nativeaudio plugins. I hope to get some clear from them. At first sight they seem to need high skills to be understood. As soon as I get some time I'll make another try.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.