Skip to content

Instantly share code, notes, and snippets.

@bhollis
Last active September 6, 2022 11:35
Show Gist options
  • Save bhollis/05fa5870d41d96e07aff to your computer and use it in GitHub Desktop.
Save bhollis/05fa5870d41d96e07aff to your computer and use it in GitHub Desktop.
A simple interface for playing raw audio samples via the Web Audio API. Meant to mimic the API from dynamicaudio.js.
# The WebAudio object can be used to write raw stereo sound samples.
#
# It has one property, "supported" which returns whether the Web Audio API
# is supported, and one method, "writeStereo" which will play sound samples.
class WebAudio
constructor: ->
if window.AudioContext? || window.webKitAudioContext?
@context = new (window.AudioContext ? window.webKitAudioContext)
@supported = true
else
@supported = false
# Given two Float32Arrays representing samples for the left
# and right stereo channel, this will immediately play them.
writeStereo: (samplesL, samplesR) ->
bufferSize = samplesL.length
buffer = @context.createBuffer(2, bufferSize, 44100)
if buffer.copyToChannel?
buffer.copyToChannel(samplesL, 0)
buffer.copyToChannel(samplesR, 1)
else
left = buffer.getChannelData(0)
right = buffer.getChannelData(1)
for i in [0..bufferSize]
left[i] = samplesL[i]
right[i] = samplesR[i]
source = @context.createBufferSource()
source.buffer = buffer
source.connect(@context.destination)
if source.start?
source.start(0)
else
source.noteOn(0)
window.WebAudio = WebAudio
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment