音訊媒體來源擴充功能

Dale Curtis
Dale Curtis

簡介

媒體來源擴充功能 (MSE) 為 HTML5 <audio> 和 <video> 元素提供擴充緩衝和播放控制項功能。雖然最初是為了促進基於 HTTP 的動態自動調整串流 (DASH) 影片播放器而開發,但我們將在下方說明如何將其用於音訊,特別是無間隙播放。

你可能聽過曲目之間流暢銜接的音樂專輯,甚至現在就正在聽。藝人會創造這種無縫播放體驗,這既是藝術選擇,也是黑膠唱片和 CD 的產物,因為音訊是以連續串流的形式寫入。不過,由於 MP3 和 AAC 等現代音訊轉碼器的運作方式,這種流暢的聽覺體驗往往會消失。

我們會在下文詳細說明原因,但現在先從示範開始。以下是精彩的《Sintel》前三十秒,切成五個獨立的 MP3 檔案,並使用 MSE 重新組合。紅線表示在建立 (編碼) 每個 MP3 時產生的間隔,您會在這些點聽到雜音。

示範模式

噁!這不是很好的體驗,我們應該可以做得更好。只要稍加調整,使用上述示範中完全相同的 MP3 檔案,我們就能使用 MSE 移除這些惱人的間隔。在下一個示範中,綠線表示檔案已合併,且間隔已移除。在 Chrome 38 以上版本中,這項功能可順暢播放!

示範模式

建立無縫內容的方式有很多種。在本次示範中,我們將著重於一般使用者可能擁有的檔案類型。每個檔案都經過單獨編碼,不考慮前後的音訊片段。

基本設定

首先,讓我們回到基本設定,說明如何設定 MediaSource 執行個體。顧名思義,Media Source Extensions 只是現有媒體元素的擴充功能。在下方,我們將代表 MediaSource 執行個體的 Object URL 指派給音訊元素的來源屬性,就像設定標準網址一樣。

var audio = document.createElement('audio');
var mediaSource = new MediaSource();
var SEGMENTS = 5;

mediaSource.addEventListener('sourceopen', function () {
  var sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');

  function onAudioLoaded(data, index) {
    // Append the ArrayBuffer data into our new SourceBuffer.
    sourceBuffer.appendBuffer(data);
  }

  // Retrieve an audio segment via XHR.  For simplicity, we're retrieving the
  // entire segment at once, but we could also retrieve it in chunks and append
  // each chunk separately.  MSE will take care of assembling the pieces.
  GET('sintel/sintel_0.mp3', function (data) {
    onAudioLoaded(data, 0);
  });
});

audio.src = URL.createObjectURL(mediaSource);

MediaSource 物件連線後,會執行一些初始化作業,最後觸發 sourceopen 事件,此時我們就可以建立 SourceBuffer。在上述範例中,我們建立 audio/mpeg,可剖析及解碼 MP3 區隔;另外還有其他類型可供使用。

異常波形

我們稍後會回到程式碼,但現在先仔細查看剛才附加的檔案,特別是檔案結尾。下圖顯示 sintel_0.mp3 音軌中,兩個聲道最後 3, 000 個樣本的平均值。紅線上的每個像素都是[-1.0, 1.0]範圍內的浮點樣本。

mp3 間隔

為什麼會有這麼多零 (無聲) 樣本?實際上,這是編碼期間產生的壓縮不自然感。幾乎所有編碼器都會引入某種形式的邊框間距。在本例中,LAME 在檔案結尾處新增了 576 個邊框間距樣本。

除了結尾的邊框間距外,每個檔案的開頭也加上了邊框間距。如果我們查看 sintel_1.mp3 音軌,會發現前端還有 576 個樣本的邊框間距。邊框間距的大小會因編碼器和內容而異,但我們可以根據每個檔案中包含的 metadata 知道確切的值。

mp3 間隔結束

每個檔案開頭和結尾的靜音部分,就是上一個示範中片段之間出現故障的原因。為了實現無縫播放,我們需要移除這些靜音部分。幸好,使用 MediaSource 就能輕鬆完成這項操作。接下來,我們會修改 onAudioLoaded() 方法,使用附加視窗和時間戳記偏移來移除這段無聲片段。

範例程式碼

function onAudioLoaded(data, index) {
  // Parsing gapless metadata is unfortunately non trivial and a bit messy, so
  // we'll glaze over it here; see the appendix for details.
  // ParseGaplessData() will return a dictionary with two elements:
  //
  //    audioDuration: Duration in seconds of all non-padding audio.
  //    frontPaddingDuration: Duration in seconds of the front padding.
  //
  var gaplessMetadata = ParseGaplessData(data);

  // Each appended segment must be appended relative to the next.  To avoid any
  // overlaps, we'll use the end timestamp of the last append as the starting
  // point for our next append or zero if we haven't appended anything yet.
  var appendTime = index > 0 ? sourceBuffer.buffered.end(0) : 0;

  // Simply put, an append window allows you to trim off audio (or video) frames
  // which fall outside of a specified time range.  Here, we'll use the end of
  // our last append as the start of our append window and the end of the real
  // audio data for this segment as the end of our append window.
  sourceBuffer.appendWindowStart = appendTime;
  sourceBuffer.appendWindowEnd = appendTime + gaplessMetadata.audioDuration;

  // The timestampOffset field essentially tells MediaSource where in the media
  // timeline the data given to appendBuffer() should be placed.  I.e., if the
  // timestampOffset is 1 second, the appended data will start 1 second into
  // playback.
  //
  // MediaSource requires that the media timeline starts from time zero, so we
  // need to ensure that the data left after filtering by the append window
  // starts at time zero.  We'll do this by shifting all of the padding we want
  // to discard before our append time (and thus, before our append window).
  sourceBuffer.timestampOffset =
    appendTime - gaplessMetadata.frontPaddingDuration;

  // When appendBuffer() completes, it will fire an updateend event signaling
  // that it's okay to append another segment of media.  Here, we'll chain the
  // append for the next segment to the completion of our current append.
  if (index == 0) {
    sourceBuffer.addEventListener('updateend', function () {
      if (++index < SEGMENTS) {
        GET('sintel/sintel_' + index + '.mp3', function (data) {
          onAudioLoaded(data, index);
        });
      } else {
        // We've loaded all available segments, so tell MediaSource there are no
        // more buffers which will be appended.
        mediaSource.endOfStream();
        URL.revokeObjectURL(audio.src);
      }
    });
  }

  // appendBuffer() will now use the timestamp offset and append window settings
  // to filter and timestamp the data we're appending.
  //
  // Note: While this demo uses very little memory, more complex use cases need
  // to be careful about memory usage or garbage collection may remove ranges of
  // media in unexpected places.
  sourceBuffer.appendBuffer(data);
}

流暢的波形

接著,我們來看看套用附加視窗後的波形,瞭解新程式碼的成效。在下方,您可以看到 sintel_0.mp3 結尾的無聲部分 (紅色) 和 sintel_1.mp3 開頭的無聲部分 (藍色) 已移除,因此片段之間可以順暢轉換。

mp3 mid

結論

這樣一來,我們就將五個片段完美拼接成一個,示範也到此結束。在結束之前,您可能已經注意到我們的 onAudioLoaded() 方法並未考慮容器或轉碼器。也就是說,無論容器或轉碼器類型為何,所有這些技術都能發揮作用。您可以在下方重播原始示範 DASH 支援的分段 MP4,而非 MP3。

示範模式

如要進一步瞭解無間隙內容創作和中繼資料剖析,請參閱下方的附錄。您也可以探索 gapless.js,進一步瞭解這個示範背後的程式碼。

感謝您閱讀本信!

附錄 A:建立無間隙內容

要建立無間隙內容並不容易。以下將逐步說明如何建立本示範中使用的 Sintel 媒體。首先,您需要一份 Sintel 的無損 FLAC 音軌;為方便後續使用,下方提供了 SHA1。工具方面,您需要 FFmpeg、MP4Box、LAME,以及安裝 afconvert 的 OSX。

    unzip Jan_Morgenstern-Sintel-FLAC.zip
    sha1sum 1-Snow_Fight.flac
    # 0535ca207ccba70d538f7324916a3f1a3d550194  1-Snow_Fight.flac

首先,我們會將 1-Snow_Fight.flac 音軌的前 31.5 秒分割出來。我們也想在 28 秒時加入 2.5 秒的淡出效果,避免播放結束後出現任何喀噠聲。使用下方的 FFmpeg 指令列,即可完成所有這些操作,並將結果放入 sintel.flac。

    ffmpeg -i 1-Snow_Fight.flac -t 31.5 -af "afade=t=out:st=28:d=2.5" sintel.flac

接著,我們會將檔案分割成 5 個 wave 檔案,每個檔案長度為 6.5 秒。由於幾乎所有編碼器都支援擷取 wave 檔案,因此使用 wave 檔案最為簡單。同樣地,我們可以使用 FFmpeg 精確地執行這項操作,之後就會有:sintel_0.wav、sintel_1.wav、sintel_2.wav、sintel_3.wav 和 sintel_4.wav。

    ffmpeg -i sintel.flac -acodec pcm_f32le -map 0 -f segment \
           -segment_list out.list -segment_time 6.5 sintel_%d.wav

接著,我們來建立 MP3 檔案。LAME 提供多種建立無間隙內容的選項。如果您可以控制內容,建議使用 --nogap 批次編碼所有檔案,完全避免片段之間出現填充。不過,為了示範,我們需要這個邊框間距,因此會使用波形檔案的標準高畫質 VBR 編碼。

    lame -V=2 sintel_0.wav sintel_0.mp3
    lame -V=2 sintel_1.wav sintel_1.mp3
    lame -V=2 sintel_2.wav sintel_2.mp3
    lame -V=2 sintel_3.wav sintel_3.mp3
    lame -V=2 sintel_4.wav sintel_4.mp3

這樣就能建立 MP3 檔案。現在,我們來介紹如何建立片段式 MP4 檔案。我們會按照 Apple 的指示,建立專為 iTunes 製作的媒體。在下方,我們會按照操作說明,將波形檔案轉換為中繼 CAF 檔案,然後使用建議的參數,將檔案編碼為 MP4 容器中的 AAC。

    afconvert sintel_0.wav sintel_0_intermediate.caf -d 0 -f caff \
              --soundcheck-generate
    afconvert sintel_1.wav sintel_1_intermediate.caf -d 0 -f caff \
              --soundcheck-generate
    afconvert sintel_2.wav sintel_2_intermediate.caf -d 0 -f caff \
              --soundcheck-generate
    afconvert sintel_3.wav sintel_3_intermediate.caf -d 0 -f caff \
              --soundcheck-generate
    afconvert sintel_4.wav sintel_4_intermediate.caf -d 0 -f caff \
              --soundcheck-generate
    afconvert sintel_0_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
              -b 256000 -q 127 -s 2 sintel_0.m4a
    afconvert sintel_1_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
              -b 256000 -q 127 -s 2 sintel_1.m4a
    afconvert sintel_2_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
              -b 256000 -q 127 -s 2 sintel_2.m4a
    afconvert sintel_3_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
              -b 256000 -q 127 -s 2 sintel_3.m4a
    afconvert sintel_4_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
              -b 256000 -q 127 -s 2 sintel_4.m4a

現在我們有幾個 M4A 檔案,需要適當分段,才能與 MediaSource 搭配使用。在本教學課程中,我們將使用一秒的片段大小。MP4Box 會將每個分段 MP4 寫出為 sintel_#_dashinit.mp4,並附帶 MPEG-DASH 資訊清單 (sintel_#_dash.mpd),該清單可捨棄。

    MP4Box -dash 1000 sintel_0.m4a && mv sintel_0_dashinit.mp4 sintel_0.mp4
    MP4Box -dash 1000 sintel_1.m4a && mv sintel_1_dashinit.mp4 sintel_1.mp4
    MP4Box -dash 1000 sintel_2.m4a && mv sintel_2_dashinit.mp4 sintel_2.mp4
    MP4Box -dash 1000 sintel_3.m4a && mv sintel_3_dashinit.mp4 sintel_3.mp4
    MP4Box -dash 1000 sintel_4.m4a && mv sintel_4_dashinit.mp4 sintel_4.mp4
    rm sintel_{0,1,2,3,4}_dash.mpd

大功告成!現在我們有分段 MP4 和 MP3 檔案,其中包含無縫播放所需的正確中繼資料。如要進一步瞭解中繼資料的樣貌,請參閱附錄 B。

附錄 B:剖析無間隙中繼資料

就像建立無間隙內容一樣,剖析無間隙中繼資料也可能很棘手,因為沒有標準的儲存方法。以下將說明 LAME 和 iTunes 這兩種最常見的編碼器如何儲存無縫中繼資料。首先,我們來設定一些輔助方法,以及上述 ParseGaplessData() 的大綱。

    // Since most MP3 encoders store the gapless metadata in binary, we'll need a
    // method for turning bytes into integers.  Note: This doesn't work for values
    // larger than 2^30 since we'll overflow the signed integer type when shifting.
    function ReadInt(buffer) {
      var result = buffer.charCodeAt(0);
      for (var i = 1; i < buffer.length; ++i) {
        result <<= 8;
        result += buffer.charCodeAt(i);
      }
      return result;
    }

    function ParseGaplessData(arrayBuffer) {
      // Gapless data is generally within the first 512 bytes, so limit parsing.
      var byteStr = new TextDecoder().decode(arrayBuffer.slice(0, 512));

      var frontPadding = 0, endPadding = 0, realSamples = 0;

      // ... we'll fill this in as we go below.

我們會先介紹 Apple 的 iTunes 中繼資料格式,因為這種格式最容易剖析和說明。在 MP3 和 M4A 檔案中,iTunes (和 afconvert) 會寫入一小段 ASCII,如下所示:

    iTunSMPB[ 26 bytes ]0000000 00000840 000001C0 0000000000046E00

這項資訊會寫入 MP3 容器內的 ID3 標記,以及 MP4 容器內的中繼資料原子。就我們的目的而言,可以忽略第一個 0000000 符記。接下來的三個權杖分別是前端填充、結尾填充和非填充樣本總數。將每個值除以音訊的取樣率,即可得出各個值的持續時間。

// iTunes encodes the gapless data as hex strings like so:
//
//    'iTunSMPB[ 26 bytes ]0000000 00000840 000001C0 0000000000046E00'
//    'iTunSMPB[ 26 bytes ]####### frontpad  endpad    real samples'
//
// The approach here elides the complexity of actually parsing MP4 atoms. It
// may not work for all files without some tweaks.
var iTunesDataIndex = byteStr.indexOf('iTunSMPB');
if (iTunesDataIndex != -1) {
  var frontPaddingIndex = iTunesDataIndex + 34;
  frontPadding = parseInt(byteStr.substr(frontPaddingIndex, 8), 16);

  var endPaddingIndex = frontPaddingIndex + 9;
  endPadding = parseInt(byteStr.substr(endPaddingIndex, 8), 16);

  var sampleCountIndex = endPaddingIndex + 9;
  realSamples = parseInt(byteStr.substr(sampleCountIndex, 16), 16);
}

另一方面,大多數開放原始碼 MP3 編碼器會將無間隙中繼資料儲存在特殊的 Xing 標頭中,該標頭位於無聲 MPEG 影格內 (因為無聲,所以不瞭解 Xing 標頭的解碼器只會播放無聲)。可惜的是,這個標記不一定會出現,而且有許多選項欄位。在本示範中,我們可控制媒體,但實際上需要進行一些額外的合理性檢查,才能知道無間隙中繼資料何時實際可用。

首先,我們要剖析樣本總數。為求簡單,我們會從 Xing 標頭讀取這項資訊,但也可以從一般 MPEG 音訊標頭建構。Xing 標頭可標示為 Xing 或 Info 標記。這個標記後方剛好 4 個位元組有 32 位元,代表檔案中的影格總數;將這個值乘以每個影格的樣本數,即可得出檔案中的總樣本數。

    // Xing padding is encoded as 24bits within the header.  Note: This code will
    // only work for Layer3 Version 1 and Layer2 MP3 files with XING frame counts
    // and gapless information.  See the following document for more details:
    // http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header
    var xingDataIndex = byteStr.indexOf('Xing');
    if (xingDataIndex == -1) xingDataIndex = byteStr.indexOf('Info');
    if (xingDataIndex != -1) {
      // See section 2.3.1 in the link above for the specifics on parsing the Xing
      // frame count.
      var frameCountIndex = xingDataIndex + 8;
      var frameCount = ReadInt(byteStr.substr(frameCountIndex, 4));

      // For Layer3 Version 1 and Layer2 there are 1152 samples per frame.  See
      // section 2.1.5 in the link above for more details.
      var paddedSamples = frameCount * 1152;

      // ... we'll cover this below.

取得樣本總數後,就可以繼續讀取邊框間距樣本數。視編碼器而定,這項資訊可能會寫在 Xing 標頭中巢狀結構的 LAME 或 Lavf 標記下。這個標頭後方剛好 17 個位元組,有 3 個位元組分別代表前端和結尾邊框間距,每個位元組為 12 位元。

        xingDataIndex = byteStr.indexOf('LAME');
        if (xingDataIndex == -1) xingDataIndex = byteStr.indexOf('Lavf');
        if (xingDataIndex != -1) {
          // See http://gabriel.mp3-tech.org/mp3infotag.html#delays for details of
          // how this information is encoded and parsed.
          var gaplessDataIndex = xingDataIndex + 21;
          var gaplessBits = ReadInt(byteStr.substr(gaplessDataIndex, 3));

          // Upper 12 bits are the front padding, lower are the end padding.
          frontPadding = gaplessBits >> 12;
          endPadding = gaplessBits & 0xFFF;
        }

        realSamples = paddedSamples - (frontPadding + endPadding);
      }

      return {
        audioDuration: realSamples * SECONDS_PER_SAMPLE,
        frontPaddingDuration: frontPadding * SECONDS_PER_SAMPLE
      };
    }

這樣一來,我們就有了完整的函式,可以剖析絕大多數的無間隙內容。不過,極端案例肯定很多,因此建議您在實際工作環境中使用類似程式碼之前,務必謹慎。

附錄 C:垃圾收集

系統會根據內容類型、平台特定限制和目前的播放位置,主動垃圾收集屬於 SourceBuffer 執行個體的記憶體。在 Chrome 中,系統會先從已播放的緩衝區回收記憶體。 不過,如果記憶體用量超過平台特定限制,系統會從未播放的緩衝區中移除記憶體。

如果播放時因記憶體回收而出現時間軸間隔,間隔較小時可能會發生故障,間隔過大時則可能完全停滯。這兩種情況都會影響使用者體驗,因此請務必避免一次附加過多資料,並手動從媒體時間軸中移除不再需要的範圍。

如要移除範圍,請在每個 SourceBuffer 上使用 remove() 方法,並以秒為單位指定 [start, end] 範圍。與 appendBuffer() 類似,每個 remove() 完成後都會觸發 updateend 事件。在事件觸發前,不應發出其他移除或附加指令。

在電腦版 Chrome 中,記憶體可同時保留約 12 MB 的音訊內容和 150 MB 的影片內容。請勿在不同瀏覽器或平台之間依賴這些值,例如,這些值絕對不代表行動裝置。

垃圾收集只會影響新增至 SourceBuffers 的資料,JavaScript 變數中可緩衝的資料量沒有限制。如有需要,您也可以在相同位置重新附加相同資料。

意見回饋