Preload audio and apply css during playback

advertisements

I am looking to create sound buttons.

Have used the answer here: Buttons click Sounds

and implemented it so that the buttons are divs and created dynamically from a MySQL DB.

Does anyone know how to preload that list of sounds on page load?

Also, I want to apply a CSS class to the div when clicked and then when the audio finishes, want it to switch back to the original CSS class.

This is what I have tried. The sounds play correctly but the onended fuction does not fire.

    <script type='text/javascript'>
    $(window).load(function(){
    var baseUrl = "http://[URL HERE]";
    var audio = [<?php echo $audiostring; ?>];

    $('div.ci').click(function() {
        var i = $(this).attr('id').substring(1);
        mySound = new Audio(baseUrl + audio[i-1]).play();
        mySound.onended = function() {
        alert("The audio has ended");};

    });
    });

    </script>


If you are using HTML5 audio you can do something like the following:

 mySound.addEventListener("ended", function()
 {
      alert("The audio has ended");
 });

Edit:

Try changing the way you create the audio tag, as referenced here.

$('div.ci').click(function() {
    var i = $(this).attr('id').substring(1);
    mySound = $(document.createElement('audio'));
    mySound.src = baseUrl + audio[i-1];
    mySound.play();
    mySound.addEventListener("ended", function()
    {
      alert("The audio has ended");
    });

});