23 - WebAudio Security Updates

As you may have seen if you have read the three sections of adding different types of music playback (.SID, .YM. and .MOD) -  it is VERY IMPORTANT to note that due to (alleged) security risks, modern browsers will not allow music to play automatically, and must be "triggered" by an event - i.e. you clicking or touching the screen before audio begins.

This is true of ANY webaudio, so many of the updated webmusic players you find I have written will include this workaround!

How I normally get around this is to include the following commands at the start of my <script> section. 

For example...




document.addEventListener('click', function(){







What this does is tell the webpage to "listen" for a mouse click event on the canvas, before doing the audio, and this gets around the security restriction.


There is a little more to it if you want the visitor to understand that they have to click somewhere etc., which I'll describe next...


Normally AT THE END of the init() function, we tell the script to launch the main go() function, but we want it to wait for a mouse click, so INSTEAD we modify the init() function so that instead it goes to a new function called wait()...


THEN we add the new wait() function....


function wait(){






    mycanvas.contex.font="32px Arial";

    mycanvas.contex.fillText("CLICK OR TOUCH CANVAS TO BEGIN",74,280);


    requestAnimFrame( wait );



This gives a "waiting" screen, where the user is advised to click "here" in order to begin the audio, and then proceed to the main go() loop. 

Hopefully this will all make sense!

No comments:

Post a Comment