Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.