首页 > 解决方案 > 检测 WebAudio 声音结束

问题描述

我正在使用 javascript 构建收音机,我正在尝试为其提供不同的功能,但我需要能够检测到歌曲的结尾以使其正常工作。有没有办法做到这一点?

我已经尝试过我在网上找到的不同方法,比如 .ended 等,但我认为如果不使用 html 音频标签,这些方法就行不通。因此,我尝试制作一个音频标签,该标签对我的 js 收音机使用的源使用相同的数据,并获取文件长度以在结束时间停止我的 sourceNode 并制作一个新标签,但我一直将 null 作为数据返回,所以那也行不通。

我想做类似的事情:

 context.onended = function() {
    $.ajax({
        url: '../scripts/radio.php',
        data: {
          attr1: 'value1'
        },
        success: function(data) {
        console.log(data);

        fileChosen = true;
        setupAudioNodes();

        var request = new XMLHttpRequest();

        request.addEventListener("progress", updateProgress);
        request.addEventListener("load", transferComplete);
        request.addEventListener("error", transferFailed);
        request.addEventListener("abort", transferCanceled);

        request.open('GET', data, true);
        request.responseType = 'arraybuffer';

        // When loaded decode the data
        request.onload = function() {

            $("#title").html("Title");
            $("#album").html("Goes");
            $("#artist").html("Here");
            onWindowResize();
            $("#title, #artist, #album").css("visibility", "visible");

            // decode the data
            context.decodeAudioData(request.response, function(buffer) {
            // when the audio is decoded play the sound
            sourceNode.buffer = buffer;
            sourceNode.start(0);

            $("#freq, body").addClass("animateHue");
            //on error
            }, function(e) {
                console.log(e);
            });
        };
        request.send();

    }
    });

我希望它在歌曲结束时运行并播放下一个文件。如果我能得到当前播放歌曲的结束时间,它会起作用。

标签: javascriptweb-audio-api

解决方案


为了解决上述问题,我在设置源的函数中添加了 .ended 事件:

function setupAudioNodes() {
    // setup a analyser
    analyser = context.createAnalyser();
    // create a buffer source node
    sourceNode = context.createBufferSource();  
    //connect source to analyser as link
    sourceNode.connect(analyser);
    // and connect source to destination
    sourceNode.connect(context.destination);
    //start updating
    rafID = window.requestAnimationFrame(updateVisualization);
    //I had to place a function for the .ended event inside the function sourceNode was set up.
    sourceNode.onended = function() {
        sourceNode.stop(0);
        playFirst();
}
}

推荐阅读