Skip to content

Instantly share code, notes, and snippets.

@amundo
Last active June 8, 2020 23:39
Show Gist options
  • Save amundo/152eefb58c14534f37ca to your computer and use it in GitHub Desktop.
Save amundo/152eefb58c14534f37ca to your computer and use it in GitHub Desktop.
playing an mp3 with fetch and the web audio api
<!DOCTYPE html>
<title>play the turkey</title>
<script>
let context = new AudioContext()
let playSound = audioBuffer => {
let source = context.createBufferSource()
source.buffer = audioBuffer
source.connect(context.destination)
source.start(0)
}
loadTurkey = async () => {
try {
let response = await fetch('turkey.mp3')
let arrayBuffer = await response.arrayBuffer()
let audioBuffer = await context.decodeAudioData(arrayBuffer)
playSound(audioBuffer)
} catch(e){
console.error(e)
}
}
loadTurkey();
</script>
<!DOCTYPE html>
<title>play the turkey</title>
<script>
let context = new AudioContext()
let playSound = audioBuffer => {
let source = context.createBufferSource()
source.buffer = audioBuffer
source.connect(context.destination)
source.start(0)
}
loadTurkey = () => fetch('turkey.mp3')
.then(response => response.arrayBuffer())
.then(arrayBuffer => context.decodeAudioData(arrayBuffer))
.then(playSound)
.catch(e => console.log(e))
loadTurkey();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment