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

后端 未结 4 2040
长情又很酷
长情又很酷 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:31

    Here is a module which will do what you want.

    It is set up to play two seconds of the clip twice, with a short pause in between, then advance the starting point half a second, pause briefly again, and then play the next two seconds from the new starting point, and so on. (You can change these settings very easily in the properties at the top).

    This code expects there to be an html element with id "debug" - I used a paragraph for this. You can delete all reference to this element if you wish. (There are four of these, the line which begins var d..., and the three lines which begin d.innerHTML...).

    var VOICEWALKER = (function () {
    // properties
    var d = document.getElementById("debug");
    var audio = document.getElementsByTagName('audio')[0];
    var start = 0;
    var stop = 2;
    var advanceBy = 0.5;
    var pauseDuration = 500; // milliseconds between clips
    var intv; // reference to the setInterval timer
    var clipCount = 0; // how many times we have played this part of the clip
    var clipMax = 2; // how many times we shall play this part of the clip
    
    // methods
    var pauseFinished = function () {
        d.innerHTML = "Pause finished";
        clip();
    };
    
    var pollClip = function () {
    
        d.innerHTML = String(audio.currentTime);
    
        if (audio.currentTime > stop) {
            audio.pause();
            d.innerHTML = "Pause";
            clearInterval(intv);
    
            clipCount += 1;
            if (clipCount === clipMax) {
                clipCount = 0;
                // advance clip
                start += advanceBy;
                stop += advanceBy;
            }
    
            // pause a little
            setTimeout(pauseFinished, pauseDuration);
        }
    
    
    };
    
    var clip = function () {
        audio.currentTime = start;
        audio.play();
        intv = setInterval(pollClip, 10);
    };
    
    var init = function () {
        audio.addEventListener('canplaythrough', clip, false);
    };
    
    return {
        init : init
    };
    }());
    
    VOICEWALKER.init();
    

提交回复
热议问题