Skip to content

Instantly share code, notes, and snippets.

@youpy
Last active December 30, 2015 06:09
Show Gist options
  • Save youpy/7787430 to your computer and use it in GitHub Desktop.
Save youpy/7787430 to your computer and use it in GitHub Desktop.
A timer implementation using "onended" event dispatched to AudioBufferSourceNode and OscillatorNode
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