Last active
December 30, 2015 06:09
-
-
Save youpy/7787430 to your computer and use it in GitHub Desktop.
A timer implementation using "onended" event dispatched to AudioBufferSourceNode and OscillatorNode
This file contains hidden or 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
window.AudioContext = window.AudioContext||window.webkitAudioContext | |
class Timer | |
constructor: (@useOscillatorNode) -> | |
@url = 'http://dl.dropbox.com/u/334064/silence100ms.wav' | |
@cxt = new AudioContext | |
@gainNode = @cxt.createGain() | |
@gainNode.gain.value = 0.0 | |
@gainNode.connect(@cxt.destination) | |
@oninit = () -> | |
init: () -> | |
if @useOscillatorNode | |
@oninit() | |
else | |
request = new XMLHttpRequest | |
request.open('GET', @url, true) | |
request.responseType = 'arraybuffer' | |
request.onload = () => | |
@cxt.decodeAudioData request.response, (buf) => | |
@buffer = buf | |
@oninit() | |
request.send(null) | |
setTimeout: (fn, time) -> | |
time /= 1000.0 | |
currentTime = @cxt.currentTime | |
if @useOscillatorNode | |
source = @cxt.createOscillator() | |
else | |
source = @cxt.createBufferSource() | |
source.buffer = @buffer | |
source.loop = true | |
source.onended = fn | |
source.connect(@gainNode); | |
source.start(currentTime) | |
source.stop(currentTime + time) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment