Search code examples
javascriptaudioxmlhttprequestfetchaudiocontext

How to load audio file into AudioContext like stream?


For example i want to load 100MB mp3 file into AudioContext, and i can do that with using XMLHttpRequest.

But with this solution i need to load all file and only then i can play it, because onprogress method don't return data.

xhr.onprogress = function(e) {
   console.log(this.response); //return null 
};

Also i tried to do that with fetch method, but this way have same problem.

fetch(url).then((data) => {
   console.log(data); //return some ReadableStream in body, 
                      //but i can't find way to use that
});

There is any way to load audio file like stream in client JavaScript?


Solution

  • You need to handle the ajax response in a streaming way. there is no standard way to do this until fetch & ReadableStream have properly been implemented across all the browsers

    I'll show you the most correct way according to the new standard how you should deal with streaming a ajax response

    // only works in Blink right now
    fetch(url).then(res => {
         let reader = res.body.getReader()
         let pump = () => {
             reader.read().then(({value, done}) => {
                 value // chunk of data (push chunk to audio context)
                 if(!done) pump()
             })
         }
         pump()
    })
    

    Firefox is working on implementing streams but until then you need to use xhr and moz-chunked-arraybuffer IE/edge has ms-stream that you can use but it's more complicated