1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

オーディオファイルを簡単に再生できる関数を作った

Last updated at Posted at 2023-06-07

はじめに

オーディオファイルを簡単に再生できる関数を作ったので紹介します。

関数

コピペしてお使いください。

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 から呼び出して問題ないようです。

おわりに

指摘、提案、その他のコメントは大歓迎です。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?