javascript - js 无法监听到audio的ended事件?

 

问题描述:

使用MediaSource播放音频流,监听audio的ended无法触发

<audio id="audios"></audio>
const audioPlay = document.getElementById('audios')
const callbackQueue = []
const ms = new MediaSource();
let sb;
let isMediaInit = false;
audioPlay.src = window.URL.createObjectURL(ms)
createWebSocket(wsUrl);
ms.addEventListener('sourceopen', () => {
    sb = ms.addSourceBuffer('audio/mpeg');
    sb.addEventListener('updateend', function () {
        // Update if currentTime is slower than 1 second from the time currently buffered in sourceBuffer
        if (isMediaInit) {
            const ranges = sb.buffered;
            const bufferLength = ranges.length;
            if (bufferLength != 0) {
                // if (sb.buffered.end(0) - audioPlay.currentTime > 0.5) {
                //     audioPlay.currentTime = sb.buffered.end(0);
                //     console.log("Update currentTime!!!!");
                // }
            }
        } else {
            audioPlay.play()
            isMediaInit = true;
        }
        if (callbackQueue.length > 0 && !sb.updating) {
            sb.appendBuffer(callbackQueue.shift());
            console.log('Delayed buffer fix');
        }
    });
});
audioPlay.addEventListener('ended' ,()=>{
    console.log('ended')
},false)


sb.appendBuffer(arrayBuffer);

 

第 1 个答案:

audioPlay.addEventListener('timeupdate', function() {
    if (this.currentTime >= this.duration) {
        console.log('ended');
    }
});

vue项目中vab-query-form vab-query-form-top-panel ...