Skip to content

Instantly share code, notes, and snippets.

@nikuuchi
Created February 22, 2013 08:46
Show Gist options
  • Select an option

  • Save nikuuchi/5011836 to your computer and use it in GitHub Desktop.

Select an option

Save nikuuchi/5011836 to your computer and use it in GitHub Desktop.
Web Audio APIを少し触ってみたコード片
$ () ->
ctx = document.getElementById("demo").getContext("2d")
ctx.strokeStyle = "#000"
ctx.fillStyle = "#000"
for x in [0..8]
ctx.strokeRect x*80,0,80,280
for x in [60,140,300,380,460]
ctx.fillRect x,0,40,170
player = new Simulator()
$("#play").click () ->
player.play($("#Hz option:selected").val(),0.2)
class Simulator
constructor: () ->
@context = new webkitAudioContext()
@context.sampleRate = @sampleRate
sampleRate: 48000
note: [
262 #C3
#277 #CS3
294 #D3
#311 #DS3
330 #E3
349 #F3
#370 #FS3
392 #G3
#415 #GS3
440 #A4
495 #B4
522 #C4
]
play: (key,vol) ->
buffer = @make(@note[key],vol)
@src = @context.createBufferSource()
@src.buffer = buffer
@src.connect(@context.destination)
@src.noteOn(0)
stop: () ->
@src.noteOff()
make: (hz,vol) ->
buffer = @context.createBuffer(1, @sampleRate, @sampleRate)
data = buffer.getChannelData 0
t = @sampleRate / hz
t_half = t / 2
for i in [0..(data.length)]
data[i] = Math.sin((2*Math.PI / t) * i)
#if ((i%t)<t_half)
# data[i] = vol
#else
# data[i] = -1 *vol
return buffer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment