Skip to content

Instantly share code, notes, and snippets.

@twfarland
Created August 13, 2018 06:14
Show Gist options
  • Save twfarland/c07ef93286719a41deea6d705517d871 to your computer and use it in GitHub Desktop.
Save twfarland/c07ef93286719a41deea6d705517d871 to your computer and use it in GitHub Desktop.
web audio xylophone
function createXylophone() {
const context = new (window.AudioContext || window.webkitAudioContext)()
const oscillator = context.createOscillator()
const gain = context.createGain()
oscillator.type = 'sine'
oscillator.connect(gain)
gain.connect(context.destination)
return {
context,
oscillator,
gain
}
}
function playNote(frequency) {
const { context, oscillator, gain } = createXylophone()
const { currentTime } = context
oscillator.frequency.value = frequency
gain.gain.setValueAtTime(0, currentTime)
gain.gain.linearRampToValueAtTime(1, currentTime + 0.01)
oscillator.start(currentTime)
gain.gain.exponentialRampToValueAtTime(0.001, currentTime + 1)
oscillator.stop(currentTime + 1)
}
playNote(493.88)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment