Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScriptProcessorNode Skipping

I have the following javascript code:

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);

I am trying to access the audio loop of web-audio, much in the way that a low-level audio streaming API would work in C. This code is supposed to play a 440 Hz tone continuously until the page is closed. The code will play the tone, but after a second or two the sound skips repeatedly, suggesting I've run out of buffer space and the script isn't being called each buffer period.

I'm sure the solution to this is simple, but what's actually causing the skipping? How can I get this script to run continuously?

EDIT: The skipping goes away if I refresh the page. Is this a browser bug?

like image 642
NmdMystery Avatar asked Dec 11 '25 12:12

NmdMystery


1 Answers

Increase the buffer size of the ScriptProcessor node from 1024 to something larger. Or use 0 to let the browser choose a value for you.

Note also ScriptProcessors are deprecated, but the replacement isn't yet available. The replacement should behave better.

like image 97
Raymond Toy Avatar answered Dec 14 '25 01:12

Raymond Toy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!