Created
April 27, 2020 07:31
-
-
Save Rulexec/6c92156754d60ea48933536fdecc5242 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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