pcwu's TIL Notes


Howler.JS: Audio library for the modern web

其實在 browser 上播放音樂很簡單:

var audio = new Audio();
audio.src = "a.mp3";
audio.play()

但現在網頁愈做愈複雜,為了快速滿足進階需求,需要更厲害的工具!所以我們就直接站在巨人的肩上,使用厲害的 Library!

Howler.js

Howler.js 的 Github 星星數破7000,應該是目前最熱門的 Audio Library。看了看功能比原本 HTML Audio 強大完整許多,強調極輕量(7KB)且零 outside dependency,有興趣可以爬爬 Source Code 讀讀。

Howler.js 最簡單的例子:

var sound = new Howl({
  src: ['sound.mp3']
});

sound.play();

React Example

以下是一個 React 的例子,使用者可以隨時點選新歌曲,中斷正在播放的歌曲。

Code 是從這裡截取的: react-audio-player

大概的邏輯就是:

play: function() {

  this.setState({ isPlaying: true, isPause: false });

  if (!this.howler) {
    this.initSoundObject();
  } else {
    var songUrl = this.state.songs[this.state.currentSongIndex].url;
    if (songUrl != this.howler._src) {
      this.initSoundObject();
    } else {
      this._play();
    }
  }
},

initSoundObject: function() {
  this.clearSoundObject();
  this.setState({ isLoading: true });

  var song = this.state.songs[this.state.currentSongIndex];
  this.howler = new Howl({
    src: song.url,
    volume: this.state.volume,
    onload: this.initSoundObjectCompleted,
    onend: this.playEnd
  });
},

clearSoundObject: function() {
  if (this.howler) {
    this.howler.stop();
    this.howler = null;
  }
},

initSoundObjectCompleted: function() {
  this._play();
  this.setState({
    duration: this.howler.duration(),
    isLoading: false
  });
},

Reference