はじめに
オーディオファイルを簡単に再生できる関数を作ったので紹介します。
関数
コピペしてお使いください。
AudioPlayer.js
function AudioPlayer() {
const obj = {}
obj.ctxList = {}
obj.load = function (id, url) {
const ctxList = this.ctxList
ctxList[id] = ctxList[id] ?? {}
ctxList[id].audioCtx = new AudioContext()
fetch(url)
.then(response => response.arrayBuffer())
.then(arrayBuffer => ctxList[id].audioCtx.decodeAudioData(arrayBuffer))
.then(buffer => {
ctxList[id].buffer = buffer
})
}
obj.play = function (id) {
const ctxList = this.ctxList
ctxList[id] = ctxList[id] ?? {}
if (ctxList[id].buffer != null && ctxList[id].source == null) {
ctxList[id].source = ctxList[id].audioCtx.createBufferSource()
ctxList[id].source.buffer = ctxList[id].buffer
ctxList[id].source.connect(ctxList[id].audioCtx.destination)
ctxList[id].source.onended = () => {
ctxList[id].source = null
}
ctxList[id].source.start()
}
}
return obj
}
準備
index.html
<script src='AudioPlayer.js'></script>
<script src='main.js'></script>
main.js
const ap = AudioPlayer()
使い方
main.js
ap.load('example', 'example.wav') // ファイルを読み込み
ap.play('example') // ファイルを再生
注意点
ap.play()
の呼び出しはユーザーの操作に基づく必要があります。
そのため DOMContentLoaded
から呼び出すと動作しません。
必ず Click
などから呼び出すようにしましょう。
ap.load()
についてはDOMContentLoaded
から呼び出して問題ないようです。
おわりに
指摘、提案、その他のコメントは大歓迎です。