Skip to content

Instantly share code, notes, and snippets.

@Rulexec
Created April 27, 2020 07:31
Show Gist options
  • Save Rulexec/6c92156754d60ea48933536fdecc5242 to your computer and use it in GitHub Desktop.
Save Rulexec/6c92156754d60ea48933536fdecc5242 to your computer and use it in GitHub Desktop.
let playButton = document.createElement('button');
playButton.textContent = 'Play';
document.body.appendChild(playButton);
playButton.addEventListener('click', () => {
let audioCtx = new AudioContext();
let sampleRate = audioCtx.sampleRate;
let totalSeconds = 2;
let arrayBuffer = audioCtx.createBuffer(
1,
sampleRate * totalSeconds,
sampleRate,
);
let amplitudes = arrayBuffer.getChannelData(0);
let sinGenerator = getSin({
sampleRate,
frequency: 440,
});
for (let i = 0; i < amplitudes.length; i++) {
amplitudes[i] = sinGenerator.next().value;
}
let source = audioCtx.createBufferSource();
source.buffer = arrayBuffer;
source.connect(audioCtx.destination);
source.start();
});
function* getSin({ sampleRate, frequency }) {
let i = 0;
while (true) {
let p = i / sampleRate;
let s = Math.sin(p * 2 * Math.PI * frequency);
yield s;
i++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment