Skip to content

Instantly share code, notes, and snippets.

@t9md
Created February 7, 2019 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t9md/bb2c04268c315f512b5f599a99b53c97 to your computer and use it in GitHub Desktop.
Save t9md/bb2c04268c315f512b5f599a99b53c97 to your computer and use it in GitHub Desktop.
window.AudioContext = window.AudioContext || window.webkitAudioContext
class AudioPlayer {
constructor () {
this.context = new AudioContext()
}
// Audio 用の buffer を読み込む
getAudioBuffer (url, callback) {
const req = new XMLHttpRequest()
req.responseType = 'arraybuffer' // array buffer を指定
req.onreadystatechange = () => {
if (req.readyState === 4) {
if (req.status === 0 || req.status === 200) {
this.context.decodeAudioData(req.response, callback)
}
}
}
req.open('GET', url, true)
req.send()
}
playSound (url) {
this.getAudioBuffer(url, buffer => {
const source = this.context.createBufferSource()
source.buffer = buffer
source.connect(this.context.destination)
source.start(0)
})
}
}
const audioPlayer = new AudioPlayer()
audioPlayer.playSound(`sounds/apple.wav`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment