Skip to content

Instantly share code, notes, and snippets.

@horndude77
Last active August 15, 2023 01:40
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save horndude77/11361875 to your computer and use it in GitHub Desktop.
Save horndude77/11361875 to your computer and use it in GitHub Desktop.
Simple HTML Tone Generator
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Tone Generator</title>
<script>
var context = null;
var usingWebAudio = true;
if (typeof AudioContext !== 'undefined') {
context = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
context = new webkitAudioContext();
} else {
usingWebAudio = false;
}
var playing = false;
var osc = null;
var freq = 440;
var STEP_CONSTANT = Math.pow(2.0, 1.0/12.0);
function toggle() {
var button = document.getElementById("toggle");
if (playing && osc) {
playing = false;
osc.stop(0);
button.value = "Play";
} else {
playing = true;
osc = context.createOscillator();
osc.connect(context.destination);
osc.frequency.value = freq;
osc.start(0);
button.value = "Stop";
}
}
function updateFreq(newFreq) {
freq = newFreq;
if (osc) {
osc.frequency.value = freq;
}
var text = document.getElementById("freqText").value = freq;
var range = document.getElementById("freqRange").value = freq;
}
window.onload = function() {
if (!usingWebAudio) {
document.getElementById("audioControls").innerHTML = "<p>Web audio required.</p>"
}
}
</script>
</head>
<body>
<div id="audioControls">
<input id="freqText" type="text" value="440" onchange="updateFreq(this.value)"/>
<input type="button" value="-1 octave" onclick="updateFreq(freq / 2)"/>
<input type="button" value="-1 half-step" onclick="updateFreq(freq / STEP_CONSTANT)"/>
<input type="button" value="+1 half-step" onclick="updateFreq(freq * STEP_CONSTANT)"/>
<input type="button" value="+1 octave" onclick="updateFreq(freq * 2)"/>
<br>
<input id="freqRange" type="range" min="0" max="1760" value="440" oninput="updateFreq(this.value)"/>
<br>
<input id="toggle" type="button" value="Play" onclick="toggle()"/>
</div>
</body>
</html>
@Cody01100011
Copy link

Thank you 😍😍😍😍😍😍😍😍

@rhartzell
Copy link

Very cool! Thank you for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment