javascripthtmlaudiosoundjs

Can you perform an action at 5 seconds into playing a sound file using Sound.js?


I have my sounds created and playing my html5 page ok on all devices. I have some animations that I want to reveal when the audio reaches certain points. maybe at 5, 10 , 25 seconds.

Is that possible if so can you provide sample code to call a function at a certain time interval?


Solution

  • You could achieve this very simply using setTimeout():

    // Set up functions that will be triggered during sound playback...
    var a = function(){
        console.log("Do something after 5 seconds");
    }
    
    var b = function(){
        console.log("Do something after 10 seconds");
    }
    
    var c = function(){
        console.log("Do something after 25 seconds");
    }
    
    // Play the sound...
    createjs.Sound.play("page1");
    
    // Immediately after playing the sound, trigger the time out functions...
    setTimeout(a, 5000);  // Triggers after 5 seconds of playback
    setTimeout(b, 10000); // Triggers after 10 seconds of playback
    setTimeout(c, 25000); // Triggers after 25 seconds of playback
    

    Working example

    More information on setTimeout can be found here: http://javascript.info/tutorial/settimeout-setinterval

    setTimeout

    The syntax is: var timerId = setTimeout(func|code, delay)

    func|code – Function variable or the string of code to execute.

    delay – The delay in microseconds, 1000 microseconds = 1 second. The execution will occur after the given delay.