The JavaScript code example demonstrates how to program changes to AudioContext states for audio processing.
<!DOCTYPE html> <html> <head> <title>XoaX.net JavaScript</title> <script src="AudioContextStates.js"></script> <link rel="icon" href="data:,"> </head> <body onload="Initialize()"> <h1>AudioContext States</h1> <button id="idCreate">Create</button> <button id="idSuspend">Suspend</button> <button id="idStop">Stop</button> <p id="idTime"></p> </body> </html>
let gqAudioContext; let gqCreateButton; let gqSuspendButton; let gqStopButton; let gqTimeElement; function Initialize() { gqCreateButton = document.getElementById("idCreate"); gqSuspendButton = document.getElementById("idSuspend"); gqStopButton = document.getElementById("idStop"); gqTimeElement = document.getElementById("idTime"); // Disable the suspend and stop buttons gqSuspendButton.setAttribute("disabled", "disabled"); gqStopButton.setAttribute("disabled", "disabled"); gqCreateButton.onclick = () => { // Disable the button and enable the others gqCreateButton.setAttribute("disabled", "disabled"); gqSuspendButton.removeAttribute("disabled"); gqStopButton.removeAttribute("disabled"); // Create the context gqAudioContext = new AudioContext(); const kqOscillatorNode = new OscillatorNode(gqAudioContext, { type: "square", frequency: 100, }); const kqGainNode = new GainNode(gqAudioContext, { gain: 0.1 }); // Connect the node kqOscillatorNode.connect(kqGainNode); kqGainNode.connect(gqAudioContext.destination); // Start the sound kqOscillatorNode.start(0); // Log any state changes gqAudioContext.onstatechange = function () { console.log(gqAudioContext.state); } } gqSuspendButton.onclick = () => { if (gqAudioContext.state === "running") { gqAudioContext.suspend().then(() => { gqSuspendButton.textContent = "Resume"; }); } else if (gqAudioContext.state === "suspended") { gqAudioContext.resume().then(() => { gqSuspendButton.textContent = "Suspend"; }); } }; gqStopButton.onclick = () => { gqAudioContext.close().then(() => { gqCreateButton.removeAttribute("disabled"); gqSuspendButton.setAttribute("disabled", "disabled"); gqSuspendButton.textContent = "Suspend"; gqStopButton.setAttribute("disabled", "disabled"); }); } DisplayTime(); } function DisplayTime() { if (gqAudioContext && gqAudioContext.state !== "closed") { gqTimeElement.textContent = `Time: ${gqAudioContext.currentTime.toFixed(3)}`; } else { gqTimeElement.textContent = "Time: No context exists."; } requestAnimationFrame(DisplayTime); }
© 20072025 XoaX.net LLC. All rights reserved.