Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Simple Tone Generator</title> </head> <body> <h1>Simple Tone Generator</h1> <button onclick="playTone()">Play Tone</button> <button onclick="stopTone()">Stop Tone</button> <script> let audioContext; let oscillator; function playTone() { if (!audioContext) { audioContext = new (window.AudioContext || window.webkitAudioContext)(); } if (!oscillator) { oscillator = audioContext.createOscillator(); oscillator.type = "sine"; // Sine wave — other values are 'square', 'sawtooth', 'triangle' oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4 note, 440 Hz oscillator.connect(audioContext.destination); oscillator.start(); } } function stopTone() { if (oscillator) { oscillator.stop(); oscillator.disconnect(); oscillator = null; // Reset the oscillator to allow a new one to be created next time } } </script> </body> </html>