Web Audio - chords
play synth chords
by jdhenckel
HTML
Gain
<input type="range" min="0" max="100" onchange="setup()">
<br> Type
<select onchange="setup()">
<option value="sine">sine</option>
<option value="square">square</option>
<option value="sawtooth">sawtooth</option>
<option value="triangle">triangle</option>
<option value="custom">custom</option>
</select>
<hr> C C+ D E- E F F+ G A- A B- B C
<br>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<br>
<button onclick="play()">play</button>
<button onclick="stop()">stop</button>
<hr>
<p>
</p>
CSS
body,
select,
input,
button {
font: 20px arial;
}
JavaScript
let audio = new(window.AudioContext || window.webkitAudioContext)();
let g1 = audio.createGain();
g1.gain.value = 0.5;
g1.connect(audio.destination);
let m = 1;
let voice = [];
function setup() {
let n = $('input')[0].value * 0.01;
g1.gain.value = n;
}
function play() {
stop();
let eps = Math.pow(2, 1 / 12);
$('p')[0].innerHTML = '';
let list = $('[type=checkbox]');
for (i = 0; i < list.length; ++i) {
if (list[i].checked) {
let s1 = audio.createOscillator();
let f = 440 * Math.pow(eps, i);
f = Math.round(f * 10) / 10;
s1.frequency.value = f;
s1.type = $('select')[0].value;
s1.start();
s1.connect(g1);
voice.push(s1);
$('p')[0].innerHTML += ' ' + f;
}
}
setup();
}
function stop() {
g1.gain.value = 0;
for (v of voice) {
v.disconnect(g1);
v.stop();
}
voice = [];
}