Play sound Javascript

Hi guys,

I am trying to play sound only under specific conditions, so I need to do it in JavaSript. The sounds are loaded in the resource library. I am trying following code but it does not seem to work:
var a = new Audio(‘Explosion.wav’)
a.play()

Any idea?

Thank you,

Petr

Hello Petr,

one could just set button to play a sound. See the screenshot or download it:
play_sound.hype.zip (23.1 KB)
It works on any event that is easy to set up in Hype.

You need to reference the audiofile with the placeholder for the media/ressource meaning ${resourcesFolderName}. This isn’t a JS variable by the way rather a Hype placeholder and gets substituted physically on export or preview with the actual folder name (based on your export script). Mostly it’s the default HYPEDOCUMENTNAME.hyperesources …

So your example only works as

var a = new Audio("${resourcesFolderName}/Explosion.wav");
a.play();

Adding this… https://howlerjs.com …to your project might help. I don’t use JavaScript libraries too often, but that’s one I like.

To pile on to all the other good advice, note that a lot of browsers are restricting playback of audio unless it happens under the context of a user event (like a mouse click or touch) first. You may want to check the console.log and see if that is happening.