Add play/pause button and compressor

This commit is contained in:
Will Greenberg 2022-08-23 14:48:35 -07:00
parent ae3346c73a
commit 04c255d9db
2 changed files with 21 additions and 3 deletions

View file

@ -43,4 +43,5 @@ p {
letters are louder, non-letters are silent.</p>
</div>
</div>
<button id="play">Play/Stop</button>
</html>

View file

@ -8,7 +8,7 @@ async function loadBuffer(ctx, path) {
function createBufferSource(ctx, buffer) {
let source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(ctx.destination);
source.connect(ctx.compressor);
return source;
}
@ -158,6 +158,15 @@ function crossProduct(a, b) {
window.addEventListener('load', async () => {
loadHash();
const ctx = new AudioContext();
const compressor = new DynamicsCompressorNode(ctx, {
threshold: -50,
knee: 40,
ratio: 12,
attack: 0,
release: 0.25,
});
compressor.connect(ctx.destination);
ctx.compressor = compressor;
const piano = new Piano('CDEFGAB');
const beats = new Beats();
await piano.init(ctx);
@ -166,10 +175,18 @@ window.addEventListener('load', async () => {
const pianoSequencer = setupSequencer(piano, 'piano');
const beatsSequencer = setupSequencer(beats, 'beats');
let stopped = true;
document.getElementById('play').addEventListener('click', () => {
stopped = !stopped;
});
const bpm = 240;
const msPerBeat = (1 / bpm) * 60 * 1000;
setInterval(() => {
if (!stopped) {
pianoSequencer.step();
beatsSequencer.step();
}
}, msPerBeat);
});