Web Audio API 再生サウンドの再生終了を検出する - JavaScript

Web Audio API 再生サウンドの再生終了を検出するコードを紹介します。

概要

Web Audio API 再生サウンドの終了を検出する場合は、オーディオソース(AudioBufferSourceNode)のOnEndedイベントを実装することで検出できます。

プログラム例

コード

下記のHTMLファイルを作成します。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title></title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, user-scale=yes, initial-scale=1.0, maximum-scale=5.0" />

  <script type="text/javascript">
    var request;
    var context;
    var stopflag = 0;

    function clickPlay() {
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      context = new AudioContext();
      context.createBufferSource().start(0);

      request = new XMLHttpRequest();
      request.open("GET", "sound3.flac", true);
      request.responseType = "arraybuffer";
      request.onload = completeOnLoad;
      request.send();
    };

    function completeOnLoad() {
      var elem = document.getElementById("Play");
      elem.innerText = "再生中";
      source = context.createBufferSource();

      // オーディオをデコード
      context.decodeAudioData(request.response, function (buf) {
        source.buffer = buf;
        source.loop = false;
        source.connect(context.destination);

        source.onended = function () {
            var msgelem = document.getElementById("message");
            msgelem.innerText = "再生が終了しました。";
        };

        source.start(0);
      });
    }

    function clickPause() {
        if (stopflag == 0) {
            context.suspend();
            stopflag = 1;
        } else {
            context.resume();
            stopflag = 0;
        }
    }
  </script>
</head>
<body>
  <a id="Play" href="javascript:void(0);" onclick="clickPlay();">読み込み</a><br />
  <a id="Pause" href="javascript:void(0);" onclick="clickPause();">停止/再開</a><br />
  <div id="message"></div>
</body>
</html>

解説

Web Audio APIを利用したサウンド再生については「Web Audio API を利用してWebブラウザーでオーディオファイルを再生する (Microsoft Edge, Google Chrome用) (JavaScript プログラミング)」または 「iOSのMobile SafariでWeb Audio API を利用してサウンドを再生する (JavaScript プログラミング)」の記事を参照してください。 また、サウンドの停止処理はこちらの記事を参照してください。

createBufferSource() メソッドを呼び出し、AudioBufferSourceNodeオブジェクトの作成後、onednded イベントを実装しています。イベント発生時に、"message" id の要素を取得し「再生が終了しました」のテキストを要素に表示するコードを記述しています。
source = context.createBufferSource();

context.decodeAudioData(request.response, function (buf) {
  source.buffer = buf;
  source.loop = false;
  source.connect(context.destination);

  source.onended = function () {
      var msgelem = document.getElementById("message");
      msgelem.innerText = "再生が終了しました。";
  };

  source.start(0);
});

実行結果

上記のHTMLファイルをWebブラウザで表示します。下図のページが表示されます。


[読み込み]リンクをクリックするとサウンドファイルを読み込み再生が始まります。リンクの文字列が[再生中]に変わります。


再生が終了すると、画面の下部に[再生が終了しました。]の文字列が表示されます。


著者
iPentec.com の代表。ハードウェア、サーバー投資、管理などを担当。
Office 365やデータベースの記事なども担当。
最終更新日: 2024-01-07
作成日: 2019-09-01
iPentec all rights reserverd.