Subscribed unsubscribe Subscribe Subscribe

Augmented Usamimi

it { is_expected.to be_blog.written_by(izumin5210) }

Web Audio APIとFetch APIで音を鳴らすスニペット

JavaScript Web Audio

Web Audio APIとFetch API

HTML5 RocksのサンプルFetch APIを利用して書き換えたもの.エラーハンドリングは面倒なので省略.

以下のスニペットFlowのtype annotationがついているので,Flowを使わない場合はいい感じに省略すること.

export default class SoundPlayer {
  static AudioContext = window.AudioContext || window.webkitAudioContext;

  uri: string;
  context: AudioContext;
  buffer: AudioBuffer;

  constructor(uri: string) {
    this.uri = uri;
    this.context = new SoundPlayer.AudioContext();
  }

  fetch(): Promise<AudioBuffer> {
    return fetch(this.uri)
      .then(res => res.arrayBuffer())
      .then(data => this.context.decodeAudioData(data))
      .then(buf => (this.buffer = buf));
  }

  play() {
    const source = this.context.createBufferSource();
    source.buffer = this.buffer;
    source.connect(this.context.destination);
    source.start(0);
  }
}

このクラスをimportして適当にやる.

import SoundPlayer from "./sound-player";
import soundUri from "./sound.mp3";

const player = new SoundPlayer(soundUri);
player.fetch(() => {
  player.play();
});

References

Web Audio API: Advanced Sound for Games and Interactive Apps

Web Audio API: Advanced Sound for Games and Interactive Apps