HELP WITH MediaSource

Joined
Aug 30, 2024
Messages
12
Reaction score
0
I am trying to stream video using MediaSource.
it works... but not when I use video from my weserver. what am I doing wrong?
here is the code:
JavaScript:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>MediaSource API Demo</title>
</head>
<body>

<h3>Appending .webm video chunks using the Media Source API</h3>

<section>
    <video controls autoplay width="320" height="240"></video>
    <pre id="log"></pre>
</section>


<script>
    //ORIGINAL CODE http://html5-demos.appspot.com/static/media-source.html

    //var FILE = "https://nickdesaulniers.github.io/netfix/demo/frag_bunny.mp4"; //this works!!
    var FILE = 'https://myWebsite.ca/videos/vid.mp4'; //this does not work!!
    
    let mimeCodec = "video/mp4; codecs=avc1.42E01E, mp4a.40.2";
    //mimCodec = 'video/webm; codecs="vorbis,vp8"';

    var NUM_CHUNKS = 5;
    var video = document.querySelector('video');
    

    var mediaSource = new MediaSource();

    video.src = window.URL.createObjectURL(mediaSource);

    function callback(e) {
        var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);

        logger.log('mediaSource readyState: ' + this.readyState);

        GET(FILE, function(uInt8Array) {
            var file = new Blob([uInt8Array], {type: 'video/mp4'}); //video/webm
            var chunkSize = Math.ceil(file.size / NUM_CHUNKS);

            logger.log('num chunks:' + NUM_CHUNKS);
            logger.log('chunkSize:' + chunkSize + ', totalSize:' + file.size);

            // Slice the video into NUM_CHUNKS and append each to the media element.
            var i = 0;

            (function readChunk_(i) {
                var reader = new FileReader();

                // Reads aren't guaranteed to finish in the same order they're started in,
                // so we need to read + append the next chunk after the previous reader
                // is done (onload is fired).
                reader.onload = function(e)
                {

                    try
                    {
                        sourceBuffer.appendBuffer(new Uint8Array(e.target.result));
                        logger.log('appending chunk:' + i);
                    }
                    catch(e)
                    {
                        console.log(e);
                    }

                    if (i == NUM_CHUNKS - 1)
                    {
                        if(!sourceBuffer.updating)
                             mediaSource.endOfStream();
                    }
                    else
                    {
                        if (video.paused)
                        {
                            video.play(); // Start playing after 1st chunk is appended.
                        }

                        sourceBuffer.addEventListener('updateend', function(e){
                            if( i < NUM_CHUNKS - 1 )
                                readChunk_(++i);
                        });
                    } //end if
                };

                var startByte = chunkSize * i;
                var chunk = file.slice(startByte, startByte + chunkSize);

                reader.readAsArrayBuffer(chunk);
            })(i);  // Start the recursive call by self calling.
        });
    }

    mediaSource.addEventListener('sourceopen', callback, false);
//    mediaSource.addEventListener('webkitsourceopen', callback, false);
//
//    mediaSource.addEventListener('webkitsourceended', function(e) {
//        logger.log('mediaSource readyState: ' + this.readyState);
//    }, false);

    function GET(url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'arraybuffer';
        xhr.send();

        xhr.onload = function(e) {
            if (xhr.status != 200) {
                alert("Unexpected status code " + xhr.status + " for " + url);
                return false;
            }
            callback(new Uint8Array(xhr.response));
        };
    }
</script>
<script>
    function Logger(id) {
        this.el = document.getElementById('log');
    }
    Logger.prototype.log = function(msg) {
        var fragment = document.createDocumentFragment();
        fragment.appendChild(document.createTextNode(msg));
        fragment.appendChild(document.createElement('br'));
        this.el.appendChild(fragment);
    };

    Logger.prototype.clear = function() {
        this.el.textContent = '';
    };

    var logger = new Logger('log');
</script>
</body>
</html>
 
Joined
Jul 4, 2023
Messages
539
Reaction score
70
1733604293447.png

1733604350635.png





BTW,
 
Joined
Aug 30, 2024
Messages
12
Reaction score
0
for anyone else who is having issues with media source. My code works fine, this is the correct way to read partial data to stream media source.
I ended up downloading the video (frag_bunny.mp4) and uploading it to my website.
then, everything worked!!!
After some research I think it's because my video was an mp4, but the bunny video was fragmented mp4.
despite both having "mp4" extensions, only the fragmented video works.
So now im stuck, dunno if anyone can help?
I want to be able to upload videos to my website and stream them....
I already have upload page with a progress bar so you can upload large files....
but for streaming I need a code to fragment the mp4.
Im starting to think this limitation makes Media Source not ideal.
Eventually id like to allow upload of different video formats also.
Must be a better way to divide videos in chunks to stream without needing fragmented mp4.
this while process seems overly complex...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,077
Messages
2,570,569
Members
47,205
Latest member
KelleM857

Latest Threads

Top