The JavaScript code example demonstrates how to program a ScriptProcessor node for audio processing.
<!DOCTYPE html> <html> <head> <title>XoaX.net JavaScript</title> <script src="ScriptProcessor.js"></script> </head> <body onload="Initialize()"> <h1>Adding Noise With a ScriptProcessorNode</h1> <button id="idPlay">Play with added noise</button> </body> </html>
let gqAudioContext; function Initialize() { const kqPlayButton = document.getElementById("idPlay"); kqPlayButton.addEventListener("click", () => { if (!gqAudioContext) { Play(); } }); } async function Play() { gqAudioContext = new AudioContext(); const kqBufferSourceNode = gqAudioContext.createBufferSource(); // Fill the buffer try { const kqResponse = await fetch("WalhallaWagner.mp3"); const kqArrayBuffer = await kqResponse.arrayBuffer(); kqBufferSourceNode.buffer = await gqAudioContext.decodeAudioData(kqArrayBuffer); } catch (qException) { console.error("Audio file load failed: " + err.message); } // Create the ScriptProcessor node with 4096 samples and one input and one output channel. const kqScriptProcessorNode = gqAudioContext.createScriptProcessor(4096, 1, 1); // Create an event listener to process the audio kqScriptProcessorNode.addEventListener("audioprocess", (qEvent) => { let qInputBuffer = qEvent.inputBuffer; let qOutputBuffer = qEvent.outputBuffer; // There is only one input and one output channel let qInputData = qInputBuffer.getChannelData(0); let qOutputData = qOutputBuffer.getChannelData(0); for (let iSample = 0; iSample < qInputData.length; ++iSample) { // Add a little noise to the input qOutputData[iSample] = qInputData[iSample] + (Math.random() * 2 - 1) * 0.1; } }); // Clean up when it is done kqBufferSourceNode.addEventListener("ended", () => { kqBufferSourceNode.disconnect(kqScriptProcessorNode); kqScriptProcessorNode.disconnect(gqAudioContext.destination); }); kqBufferSourceNode.connect(kqScriptProcessorNode); kqScriptProcessorNode.connect(gqAudioContext.destination); kqBufferSourceNode.start(); }
© 20072025 XoaX.net LLC. All rights reserved.