phaserjs / phaser-ce

Phaser CE is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
http://phaser.io
MIT License
1.35k stars 491 forks source link

Unable to catch sound play errors when using AudioTag #590

Open josalmi opened 6 years ago

josalmi commented 6 years ago

This Issue is about a bug in the API:

Sound can only be played as a response to user interaction like click event and if you fail to do so browsers will throw errors at you. Quoting from https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play

The HTMLMediaElement.play() method attempts to begin playback of the media and returns a Promise which is fulfilled when the playback has been successfully started, and which is rejected if playback fails to begin for any reason (such as permission issues or other problems).

It seems that Phaser expects .play() to always succeed as can be seen here: https://github.com/photonstorm/phaser-ce/blob/master/src/sound/Sound.js#L721 and it would be nice to have a way to catch this. If we were able to catch this error we would be able to ask the user to interact with the game rather than failing silently as it does now. Also the game keeps reporting that the sound is playing.

josalmi commented 6 years ago

This could also affect WebAudio playback after Chrome 70: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

samme commented 6 years ago

We're a bit stuck since Phaser also supports browsers that don't return a Promise.

I think the idea is that you could check game.sound.touchLocked before trying playback.

We could either

nazimboudeffa commented 6 years ago

Do I have to use the play(...) function and don't care about if it throws an error or not or does someone have an example on how to catch an error in js ? I think this way wa have to catch the errors of all the function in the framework