skip to Main Content

Is it possible to start playing audio using MediaSource (or something) without waiting for the complete data to be received ? For example, I have a very large audio file (several hours long) served using chunked transfer encoding, and I want to play it as soon as possible while the fetching process continues.

I’ve tried to fetch using standard code from MediaSource examples, e.g this. But audio player waits for whole file to be loaded.

2

Answers


  1. Modifying the MediaSource examples code you gave, I came up with this

        const audio = document.createElement('audio');
        audio.setAttribute("controls", "controls");
        document.body.insertAdjacentElement('afterbegin', audio);
    
        if (MediaSource.isTypeSupported('audio/mp4; codecs="opus"')) {
            const mediaSource = new MediaSource();
            audio.src = URL.createObjectURL(mediaSource);
    
            mediaSource.addEventListener('sourceopen', async function () {
                URL.revokeObjectURL(audio.src);
    
                const sourceBuffer = mediaSource.addSourceBuffer('audio/mp4; codecs="opus"');
    
                const processStream = async (stream) => {
                    const reader = stream.getReader();
                    while (true) {
                        const {done, value} = await reader.read();
                        if (done) {
                            console.log("read finished");
                            return;
                        }
                        sourceBuffer.appendBuffer(value);
                    }
                }
                console.log('Fetching audio file...');
                const response = await fetch('https://storage.googleapis.com/media-session/bear-opus.mp4');
                await processStream(response.body);
            });
        }
    Login or Signup to reply.
  2. There’s no reason to do anything wild. It’s this simple:

    <audio src="https://example.com/your-stream" preload="none"></audio>
    

    The preload="none" is there for live streams, so that the browser isn’t just downloading audio it isn’t going to play. You can take it out if your stream is not live.

    Don’t bother with MediaSource Extensions. It does not gain you any functionality for this use case, and only hurts your client compatibility and codec/container choices.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search