简体   繁体   中英

playing (html5) audio on a timer

I have a page that needs to play a sound based on the value of an array (and play the whole array out). So, for example, I have an array {1, 0, 0, 0, 1, 1, 0, 1, 0} and I need them to play or pause in order, 1 = play, 0 = "pause".

I've tried a number of things so far, but just can't get it to work as I expect.

The closest I've gotten was:

$.each(myFinalList, function(i, playit){
    if(playit == 1){
        $("#results").append("Play..");
        setTimeout("playSound()", 3250);
    }
    else{
        $("#results").append("Nothing..");
        setTimeout("doNothing()", 3500);
    }
};

function playSound(){
    var snd = new Audio('');

    if(snd.canPlayType('audio/mp3')){
        snd = new Audio('sound.mp3');
    }

    snd.play();
}

function doNothing(){
    //dont do anything
}

The issue with this is that the sounds aren't playing at the proper time, almost like the doNothing() is not getting called.

Any thoughts?

Try this:

http://jsfiddle.net/ZkE8B/12/

let me know if it helps

edit: http://jsfiddle.net/ZkE8B/15/ clears the transcript on every cycle complete

It sounds like you want to iterate through each element of myFinalList in order, but with a timeout between each iteration. In this case, you probably want to do something like

function timer(index) {
    if (myFinalList[i] == 1) playSound();
    setTimeout(function() { timer(index+1); }, 3500);
}
timer(0);

which will iterate through each element of myFinalList, one at a time, every 3500 milliseconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM