How can I queue a series of sound HTML5 <audio> sound clips to play in sequence?

后端 未结 4 2038
长情又很酷
长情又很酷 2020-12-18 04:19

I\'m experimenting with porting a simple audio utility called VoiceWalker to Javascript. VoiceWalker is a tool to help people transcribe audio, and it works like this:

4条回答
  •  天涯浪人
    2020-12-18 04:36

    Follow the structure of other API's in JavaScript: have your clip function also take in a "what to do next" function. (More technical term: "callback"). The idea is that your clip function knows when it's done with its work, and can then call the callback at the right time.

    As an example, let's say that we have a function that will slowly spell out a word to the document's body:

    var spell = function(word, onSuccess) {
        var i = 0;
        var intervalId = setInterval(function() { 
                        if (i >= word.length) { 
                            clearInterval(intervalId);
                            onSuccess();
                        } else {
                            document.body.appendChild(
                                document.createTextNode(word.charAt(i)));
                            i++;
                        }
                    }, 100)
    };
    

    When this computation finishes spelling out the word, it will call onSuccess, which is going to be our callback. Once we have spell(), we can try to use it:

    var startIt = function() {
        spell("hello", afterHello);
    };
    
    var afterHello = function() {
        spell("world", afterHelloWorld);
    };
    
    var afterHelloWorld = function() {
        alert("all done!"); 
    };
    

    Try calling startIt and you'll see it do its thing.

    This approach allows us to chain together these asynchronous computations. Every good JavaScript asynchronous API allows you to define "what to do next" after the computation succeeds. You can write your own functions to do the same.

提交回复
热议问题