Amit Amit - 3 months ago 13
HTML Question

Preload audio and apply css during playback

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>

Answer

<audio> and new Audio() should be the same but it doesn't look like that is the case in practice. Whenever I need to create an audio object in JavaScript I actually just create an element like this:

The ended event is created based on .currentTime attribute. event-media-ended

code complete use closest

<style type="text/css">
   div
    {
        width: 100px;
        height: 100px;
        background: #cdaaaa;
    }
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >

</div>
<div >

</div>
<div >

</div>
 <script type="text/javascript">

 $(window).load(function(){
    var baseUrl = "http://www.soundjay.com/button/";
    var audios = ["beep-01a.mp3", "beep-02.mp3", "beep-03.mp3", "beep-04.mp3", "beep-05.mp3", "beep-06.mp3", "beep-07.mp3", "beep-08b.mp3", "beep-09.mp3"];


   $(window).load(function(){
var baseUrl = "http://www.soundjay.com/button/";
var audios = ["beep-01a.mp3", "beep-02.mp3", "beep-03.mp3", "beep-04.mp3", "beep-05.mp3", "beep-06.mp3", "beep-07.mp3", "beep-08b.mp3", "beep-09.mp3"];


$('div').click(function(event) {

    $(this).css('background', 'blue');
    var audio = document.createElement('audio');
    var item = audios[Math.floor(Math.random()*audios.length)]; //sound random 
    audio.src = baseUrl +item;
    audio.play();

    audio.addEventListener("ended", function(){
         audio.currentTime = 0;
         $(event.target).closest('div').css('background', '#cdaaaa');
    });

});

});