Created
February 7, 2019 09:21
-
-
Save t9md/bb2c04268c315f512b5f599a99b53c97 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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