如何主動預先載入資源,加快媒體播放速度。
播放速度越快,代表觀看影片或聆聽音訊的人數越多。這是已知的事實。本文將探討幾項技巧,有助您根據自己的用途主動預先載入資源,進而加快音訊和影片播放速度。
我會說明預先載入媒體檔案的三種方法,先從其優缺點開始說明。
很好... | 不過... | |
---|---|---|
影片預先載入屬性 | 這個簡單的外掛程式能輕鬆用於網路伺服器代管的專屬檔案。 | 瀏覽器可能會完全忽略這個屬性。 |
載入並剖析 HTML 文件後,系統就會開始擷取資源。 | ||
Media Source Extensions (MSE) 會忽略媒體元素的 preload 屬性,因為應用程式負責向 MSE 提供媒體。 |
||
連結預先載入 |
強制瀏覽器發出影片資源要求,而不會封鎖文件的 onload 事件。 |
HTTP 範圍要求不相容。 |
與 MSE 和檔案區隔相容。 | 這僅適用於擷取完整資源時的小型媒體檔案 (小於 5 MB)。 | |
手動緩衝 | 完全控制 | 網站必須負責處理複雜的錯誤。 |
影片預先載入屬性
如果影片來源是代管於網路伺服器上的不重複檔案,建議您使用影片 preload
屬性,向瀏覽器說明要預先載入哪些資訊或內容。這表示媒體來源擴充功能 (MSE) 與 preload
不相容。
只有在初始 HTML 文件完全載入並剖析 (例如已觸發 DOMContentLoaded
事件) 時,系統才會啟動資源擷取作業,而截然不同的 load
事件則只會在資源實際擷取時觸發。
將 preload
屬性設為 metadata
表示預期使用者不需要影片,但擷取其中繼資料 (維度、曲目清單、影片長度等) 是理想做法。請注意,從 Chrome 64 開始,preload
的預設值是 metadata
。(先前為 auto
)。
<video id="video" preload="metadata" src="file.mp4" controls></video>
<script>
video.addEventListener('loadedmetadata', function() {
if (video.buffered.length === 0) return;
const bufferedSeconds = video.buffered.end(0) - video.buffered.start(0);
console.log(`${bufferedSeconds} seconds of video are ready to play.`);
});
</script>
將 preload
屬性設為 auto
,表示瀏覽器可以快取完整播放的資料,不必停止緩衝處理。
<video id="video" preload="auto" src="file.mp4" controls></video>
<script>
video.addEventListener('loadedmetadata', function() {
if (video.buffered.length === 0) return;
const bufferedSeconds = video.buffered.end(0) - video.buffered.start(0);
console.log(`${bufferedSeconds} seconds of video are ready to play.`);
});
</script>
但有一些注意事項。這只是提示,瀏覽器可能會完全忽略 preload
屬性。撰寫本文件時,以下是一些在 Chrome 中套用的規則:
- 啟用「Data Saver」時,Chrome 會將
preload
值強制設為none
。 - 在 Android 4.3 中,由於 Android 錯誤,Chrome 會將
preload
值強制設為none
。 - 在行動網路連線 (2G、3G 和 4G) 上,Chrome 會將
preload
值強制設為metadata
。
提示
如果您的網站包含相同網域中的許多影片資源,建議您將 preload
值設為 metadata
,或是定義 poster
屬性,並將 preload
設為 none
。如此一來,您就不會超過可能會等待載入資源的 HTTP 連線數量上限 (根據 HTTP 1.1 規格 6)。請注意,如果影片並非核心使用者體驗的一部分,這樣做也可以改善網頁速度。
連結預先載入
如其他文章中的「說明」所述,連結預先載入是一種宣告式擷取機制,可讓您強制瀏覽器在不封鎖 load
事件及下載頁面時發出資源要求。透過 <link rel="preload">
載入的資源會儲存在本機瀏覽器中,而且會持續中斷,直到在 DOM、JavaScript 或 CSS 明確參照這些資源為止。
預先載入與預先擷取不同,前者著重於目前的導覽,並根據類型 (指令碼、樣式、字型、影片、音訊等) 以優先順序擷取資源。可用於為目前工作階段暖機瀏覽器快取。
預先載入完整影片
以下說明如何在網站上預先載入完整影片,這樣一來,JavaScript 要求擷取影片內容時,就會從快取中讀取,因為瀏覽器可能已快取資源。如果預先載入要求尚未完成,系統會進行一般網路擷取。
<link rel="preload" as="video" href="https://cdn.com/small-file.mp4">
<video id="video" controls></video>
<script>
// Later on, after some condition has been met, set video source to the
// preloaded video URL.
video.src = 'https://cdn.com/small-file.mp4';
video.play().then(() => {
// If preloaded video URL was already cached, playback started immediately.
});
</script>
在這個範例中,影片元素會使用預先載入的資源,因此 as
預先載入連結值為 video
。如果是音訊元素,則會是 as="audio"
。
預先載入第一個片段
以下範例說明如何使用 <link
rel="preload">
預先載入影片的第一個片段,並搭配使用媒體來源擴充功能。如果您不熟悉 MSE JavaScript API,請參閱「MSE 基本概念」一文。
為求簡單起見,我們假設整部影片都已分割成較小的檔案,例如 file_1.webm
、file_2.webm
、file_3.webm
等。
<link rel="preload" as="fetch" href="https://cdn.com/file_1.webm">
<video id="video" controls></video>
<script>
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen, { once: true });
function sourceOpen() {
URL.revokeObjectURL(video.src);
const sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp09.00.10.08"');
// If video is preloaded already, fetch will return immediately a response
// from the browser cache (memory cache). Otherwise, it will perform a
// regular network fetch.
fetch('https://cdn.com/file_1.webm')
.then(response => response.arrayBuffer())
.then(data => {
// Append the data into the new sourceBuffer.
sourceBuffer.appendBuffer(data);
// TODO: Fetch file_2.webm when user starts playing video.
})
.catch(error => {
// TODO: Show "Video is not available" message to user.
});
}
</script>
支援
您可以使用下列程式碼片段偵測 <link rel=preload>
對各種 as
類型的支援:
function preloadFullVideoSupported() {
const link = document.createElement('link');
link.as = 'video';
return (link.as === 'video');
}
function preloadFirstSegmentSupported() {
const link = document.createElement('link');
link.as = 'fetch';
return (link.as === 'fetch');
}
手動緩衝
在我們深入探討 Cache API 和服務 Worker 前,先來看看如何使用 MSE 手動為影片緩衝。以下範例假設您的網路伺服器支援 HTTP Range
要求,但與檔案區隔類似。請注意,部分中介軟體程式庫 (例如 Google 的 Shaka Player、JW Player 和 Video.js) 會自動為您處理。
<video id="video" controls></video>
<script>
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen, { once: true });
function sourceOpen() {
URL.revokeObjectURL(video.src);
const sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp09.00.10.08"');
// Fetch beginning of the video by setting the Range HTTP request header.
fetch('file.webm', { headers: { range: 'bytes=0-567139' } })
.then(response => response.arrayBuffer())
.then(data => {
sourceBuffer.appendBuffer(data);
sourceBuffer.addEventListener('updateend', updateEnd, { once: true });
});
}
function updateEnd() {
// Video is now ready to play!
const bufferedSeconds = video.buffered.end(0) - video.buffered.start(0);
console.log(`${bufferedSeconds} seconds of video are ready to play.`);
// Fetch the next segment of video when user starts playing the video.
video.addEventListener('playing', fetchNextSegment, { once: true });
}
function fetchNextSegment() {
fetch('file.webm', { headers: { range: 'bytes=567140-1196488' } })
.then(response => response.arrayBuffer())
.then(data => {
const sourceBuffer = mediaSource.sourceBuffers[0];
sourceBuffer.appendBuffer(data);
// TODO: Fetch further segment and append it.
});
}
</script>
注意事項
既然現在您可以掌控整個媒體緩衝處理體驗,建議您在考慮預先載入時,考慮裝置的電池電量、「數據節省模式」的使用者偏好設定和網路資訊。
電池感知
在考慮預先載入影片前,請先考量使用者裝置的電池電量。這樣就可以在電量不足時延長電池續航力。
在裝置電力耗盡時,停用預先載入或至少預先載入解析度較低的影片。
if ('getBattery' in navigator) {
navigator.getBattery()
.then(battery => {
// If battery is charging or battery level is high enough
if (battery.charging || battery.level > 0.15) {
// TODO: Preload the first segment of a video.
}
});
}
偵測「數據節省模式」
使用 Save-Data
用戶端提示要求標頭,為在瀏覽器中選擇啟用「節省數據」模式的使用者提供快速且輕量的應用程式。識別這個要求標頭後,您的應用程式就能自訂,並為受限於成本和效能不足的使用者提供最佳的使用者體驗。
詳情請參閱透過儲存資料提供快速且輕量的應用程式。
根據網路資訊的智慧載入
建議先檢查 navigator.connection.type
再預先載入。設為 cellular
時,您可以避免預先載入,並建議使用者行動網路業者可能會收取頻寬費用,並只自動播放先前快取的內容。
if ('connection' in navigator) {
if (navigator.connection.type == 'cellular') {
// TODO: Prompt user before preloading video
} else {
// TODO: Preload the first segment of a video.
}
}
請查看網路資訊範例,瞭解如何同時回應網路變更。
預先快取多個第一個區隔
我想推測預先載入某些媒體內容,但又不曉得使用者最終會選擇哪個媒體呢?如果使用者所在的網頁包含 10 部影片,我們可能就有足夠的記憶體,可以從每個片段擷取一個區段檔案,但我們絕對不應建立 10 個隱藏的 <video>
元素和 10 個 MediaSource
物件,並開始提供這些資料。
以下兩個部分的範例說明如何使用功能強大且易於使用的 Cache API,預先快取影片的多個第一段。請注意,IndexedDB 也可以達到類似的目標。我們尚未使用 Service Worker,因為也可以透過 window
物件存取 Cache API。
擷取和快取
const videoFileUrls = [
'bat_video_file_1.webm',
'cow_video_file_1.webm',
'dog_video_file_1.webm',
'fox_video_file_1.webm',
];
// Let's create a video pre-cache and store all first segments of videos inside.
window.caches.open('video-pre-cache')
.then(cache => Promise.all(videoFileUrls.map(videoFileUrl => fetchAndCache(videoFileUrl, cache))));
function fetchAndCache(videoFileUrl, cache) {
// Check first if video is in the cache.
return cache.match(videoFileUrl)
.then(cacheResponse => {
// Let's return cached response if video is already in the cache.
if (cacheResponse) {
return cacheResponse;
}
// Otherwise, fetch the video from the network.
return fetch(videoFileUrl)
.then(networkResponse => {
// Add the response to the cache and return network response in parallel.
cache.put(videoFileUrl, networkResponse.clone());
return networkResponse;
});
});
}
請注意,如果我使用 HTTP Range
要求,就必須手動重新建立 Response
物件,因為 Cache API「尚未」支援 Range
回應。請注意,呼叫 networkResponse.arrayBuffer()
一次會將回應的完整內容一次擷取至轉譯器記憶體,因此建議您使用較小的範圍。
我修改了上述範例的一部分,將 HTTP 範圍要求儲存至影片友善快取,供您參考。
...
return fetch(videoFileUrl, { headers: { range: 'bytes=0-567139' } })
.then(networkResponse => networkResponse.arrayBuffer())
.then(data => {
const response = new Response(data);
// Add the response to the cache and return network response in parallel.
cache.put(videoFileUrl, response.clone());
return response;
});
播放影片
當使用者按一下播放按鈕時,我們會擷取 Cache API 中的第一段影片,如果有可用影片會立即開始播放。否則,我們只會從網路擷取該資訊。請注意,瀏覽器和使用者可能會決定清除「快取」。
如前所述,我們使用 MSE 將影片的第一個片段傳入影片元素。
function onPlayButtonClick(videoFileUrl) {
video.load(); // Used to be able to play video later.
window.caches.open('video-pre-cache')
.then(cache => fetchAndCache(videoFileUrl, cache)) // Defined above.
.then(response => response.arrayBuffer())
.then(data => {
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen, { once: true });
function sourceOpen() {
URL.revokeObjectURL(video.src);
const sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp09.00.10.08"');
sourceBuffer.appendBuffer(data);
video.play().then(() => {
// TODO: Fetch the rest of the video when user starts playing video.
});
}
});
}
使用 Service Worker 建立 Range 回應
如果您擷取了整個影片檔案並儲存在 Cache API 中,接下來該怎麼做?瀏覽器傳送 HTTP Range
要求時,您絕對不要將整個影片移到轉譯器記憶體中,因為 Cache API「尚未」支援 Range
回應。
現在就來示範如何攔截這些要求,並從服務工作站傳回自訂的 Range
回應。
addEventListener('fetch', event => {
event.respondWith(loadFromCacheOrFetch(event.request));
});
function loadFromCacheOrFetch(request) {
// Search through all available caches for this request.
return caches.match(request)
.then(response => {
// Fetch from network if it's not already in the cache.
if (!response) {
return fetch(request);
// Note that we may want to add the response to the cache and return
// network response in parallel as well.
}
// Browser sends a HTTP Range request. Let's provide one reconstructed
// manually from the cache.
if (request.headers.has('range')) {
return response.blob()
.then(data => {
// Get start position from Range request header.
const pos = Number(/^bytes\=(\d+)\-/g.exec(request.headers.get('range'))[1]);
const options = {
status: 206,
statusText: 'Partial Content',
headers: response.headers
}
const slicedResponse = new Response(data.slice(pos), options);
slicedResponse.setHeaders('Content-Range': 'bytes ' + pos + '-' +
(data.size - 1) + '/' + data.size);
slicedResponse.setHeaders('X-From-Cache': 'true');
return slicedResponse;
});
}
return response;
}
}
請特別注意,我使用 response.blob()
重新建立這個配量回應,因為這只是為我提供檔案的控制,而 response.arrayBuffer()
會將整個檔案帶入轉譯器記憶體。
我的自訂 X-From-Cache
HTTP 標頭可用來判斷這項要求是來自快取還是網路。ShakaPlayer 等玩家可使用忽略回應時間,做為網路速度指標。
查看官方的範例媒體應用程式,尤其是 ranged-response.js 檔案,瞭解如何處理 Range
要求的完整解決方案。