[英]Retrieve mp3 file from cache and play it in browser
我有一個我正在緩存的 mp3 文件:
const request = URL_TO_MY_MP3_FILE
caches.open("my-cache").then(cache => {
cache.add(request);
});
我可以看到 mp3 文件被緩存在 Application 選項卡中:
順便說一句,我如何確保文件的 Content-Type 緩存為audio/mp3
而不是audio/mpeg
?
稍后,我想從緩存中檢索 mp3 文件,以便在瀏覽器中播放:
caches.open("my-cache").then(cache => {
const responsePromise = cache.match(request);
responsePromise.then(result => {
console.log(result.body)
this.audio = new Audio(result.body);
const playPromise = this.audio.play();
playPromise.then(function() {
console.log('success!')
}).catch(function(error) {
console.log(error)
}.bind(this), false);
});
})
這是console.log(result.body)
的輸出:
使用new Audio(result.body)
加載 mp3 文件后,我嘗試使用this.audio.play()
播放文件,但這會導致錯誤:
DOMException: 加載失敗,因為找不到支持的源。
如何從緩存中檢索 mp3 文件並在瀏覽器中播放?
你必須打電話給reader.read()
caches.open("my-cache").then(cache => {
const responsePromise = cache.match(request);
responsePromise.then(result => {
var reader = result.body.getReader();
reader.read().then((result) => {
const mimeType = 'audio/mpeg'
const url = URL.createObjectURL(new Blob([result.value.buffer], {type: mimeType}))
this.audio = new Audio(url);
const playPromise = this.audio.play();
playPromise.then(function() {
console.log('success!')
}).catch(function(error) {
console.log(error)
}.bind(this), false);
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.