ScriptProcessorNode跳过

时间:2015-09-30 18:16:37

标签: javascript audio web-audio

我有以下javascript代码:

var audio = null;

try {
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    audio = new AudioContext();
} catch (e) {
    alert("Web Audio API is not supported in this browser");
}

var scriptNode = audio.createScriptProcessor(1024, 0, 1);

var pos = 0.0;

scriptNode.onaudioprocess = function(audioProcessingEvent) {
    var output = audioProcessingEvent.outputBuffer;

    for (var channel = 0; channel < output.numberOfChannels; channel++) {
        var data = output.getChannelData(channel);

        for (var i = 0; i < data.length; i++) {
            data[i] = Math.sin(pos);

            pos += 2.0 * 3.14159 * 440.0 / audio.sampleRate;

            while (pos >= 2.0 * 3.14159) {
                pos -= 2.0 * 3.14159;
            }
        }
    }
}

scriptNode.connect(audio.destination);

我正在尝试访问网络音频的音频循环,就像低级音频流API在C中工作一样。此代码应该连续播放440 Hz音调,直到页面关闭。代码将播放音调,但在一两秒之后声音会反复跳过,表明我的缓冲区空间不足,并且每个缓冲区都没有调用脚本。

我确信这个解决方案很简单,但究竟是什么导致了跳过?如何让这个脚本连续运行?

编辑:如果我刷新页面,跳过就会消失。这是一个浏览器错误吗?

2 个答案:

答案 0 :(得分:1)

将ScriptProcessor节点的缓冲区大小从1024增加到更大。或者使用0让浏览器为您选择一个值。

另请注意,不推荐使用ScriptProcessors,但尚未提供替换。替换应该表现得更好。

答案 1 :(得分:0)

例如,间隔为4秒,

var audio = null;

try {
    window.AudioContext = window.AudioContext ||     window.webkitAudioContext;
    audio = new AudioContext();
} catch (e) {
    alert("Web Audio API is not supported in this browser");
}

var INTERVAL = 4;  // 4 [sec]

var scriptNode = audio.createScriptProcessor(1024, 0, 1);

var pos = 0.0;

var elapsedBuffer = 0;

scriptNode.onaudioprocess = function(audioProcessingEvent) {
    var output = audioProcessingEvent.outputBuffer;

    for (var channel = 0; channel < output.numberOfChannels; channel++) {
        var data = output.getChannelData(channel);

        for (var i = 0; i < data.length; i++) {
            elapsedBuffer++;

            if (elapsedBuffer > audio.sampleRate) {
                if (elapsedBuffer > (INTERVAL * audio.sampleRate)) {
                    elapsedBuffer = 0;
                }

                data[i] = 0;

                continue;
            }

            data[i] = Math.sin(pos);

            pos += 2.0 * 3.14159 * 440.0 / audio.sampleRate;

            while (pos >= 2.0 * 3.14159) {
                pos -= 2.0 * 3.14159;
            }
        }
    }
};

scriptNode.connect(audio.destination);

XSound.js是非常有用的Web Audio API库。