不囉嗦,直接上個 google doodles 的 範例 ,還不錯玩吧~

這是什麼?

Web Audio API 是由 W3C 規範的網站音頻 API,主要應用在 網頁音樂的撥放、處理、編輯 ,在 Github 上,也可以找到大量依賴 Web Audio API 的音樂相關套件;其實這不是一項非常新的技術,第一版至今 (2011 - 2018) 也已經發展了 7 年,也所幸如此,目前主流瀏覽器皆有支援:

IE11表示:嗯?什麼支援?

為什麼要玩這個?

如果只是要在網頁上簡單的撥放音樂,現在 html5 的 <audio> 標籤已經可以簡單快速的做到這件事情,甚至還幫你生出簡單的 Player。
e.g.:

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

但如果想要在網頁上透過 Javascript 編輯、分析、甚至創造音樂,那接觸一下 Web Audio API 就是必須的了。

功能有哪些?

如同前述,Web Audio API 可以做到:

  • 各式效果器
  • 3D 音源定位計算
  • 模組化串接
  • 怎麼用啊?

    那就先來玩玩看基本的範例吧:

    首先,先建立Context,也就是 Web Audio Api 的容器:

    const AudioContext = window.AudioContext || window.webkitAudioContext // 跨瀏覽器
    const audioCtx = new AudioContext()
    

    接著建立一個振盪器,當成簡易的音源

    const oscillator = audioCtx.createOscillator() 
    

    以及增益節點,也就是控制音量的地方

    const gainNode = audioCtx.createGain() 
    

    設定聲音的參數:

    oscillator.type = 'sine' // 正弦波
    oscillator.frequency.value = 440 // A4 頻率
    oscillator.detune.value = 0 // 解諧
    gainNode.gain.value = 1 // 音量  
    

    最後把他們接在一起,可以想像成是 樂器 -> PA 台 -> 音響 那樣,

    this.oscillator.connect(this.gainNode)
    this.oscillator.start() // 啟動音源
    

    基本上設定好囉,最後是寫個按鈕,以及點擊事件的處理函式,切換聲音撥放 & 暫停:

    <button @click="clickHandler"> Play / Pause </button>
    
    clickHandler(){
      if (this.isPlaying) {
        this.gainNode.disconnect(this.audioCtx.destination)
      } else {
        this.gainNode.connect(this.audioCtx.destination)
      this.isPlaying = !this.isPlaying
    以上,就是最基本的 Web Audio API 使用範例啦。

    半路出家網站工程師;半生熟的前端加上一點點的後端。
    喜歡音樂,喜歡學習、分享,也喜歡當個遊戲宅。

    相信一切安排都是最好的路。