[英]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.