简体   繁体   中英

Retrieve mp3 file from cache and play it in browser

I have an mp3 file that I am caching as such:

const request = URL_TO_MY_MP3_FILE
caches.open("my-cache").then(cache => {
   cache.add(request);
});

I can see that the mp3 file is being cached in the Application tab: 在此处输入图像描述

By the way, how do I ensure that file is Content-Type cached as audio/mp3 and not audio/mpeg ?

Later on, I would like to retrieve the mp3 file from cache so I can play it in the browser:

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);
 });

})

This is the output of console.log(result.body) : 在此处输入图像描述

After loading the mp3 file with new Audio(result.body) I try to play the file with this.audio.play() but this results in an error:

DOMException: Failed to load because no supported source was found.

How can I retrieve the mp3 file from cache and play it in the browser?

You have to call 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);
      }); 

 });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM