2020年2月5日 星期三

Javascript 使用 html5 的 MediaSource 播放器

Chrome 與 Firefox 都支援 HTML5 的 MediaSource, 但餵進去的資料必須是 fmp4 格式的資料結構, 伺服器可以透過 mp4fragment 將 mp4 檔案一一轉換成 fmp4 格式檔再傳給客戶端. 客戶端的播放程式(javascript)利用  html 的 video 標籤播放該影音檔, 將以下程式碼存成 html 文字檔, 放在伺服器讓客戶端(Chrome 或是  Firefox)來連線:

<html><head><meta charset='utf-8'></head><body><script>
const codec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
class HttpPlayer {
    constructor (width, height) {
        const video  = document.createElement('video');
        const mediaSource = new MediaSource( );
        mediaSource.onsourceopen = _evt => {
            var  completeFile = null;
            var  number  = 1; // total number to get
            const sourceBuffer = mediaSource.addSourceBuffer(codec);
            const httpGet = _filename => {
                const url = `https://${location.origin.split("//").pop( )}${_filename}`;
                const https = new XMLHttpRequest( );
                https.responseType = 'arraybuffer';
                https.onload = ( ) => sourceBuffer.appendBuffer(https.response);
                https.onloadend = ( ) => completeFile = _duration => {
                    completeFile = null;
                    number -- <= 0 ?  mediaSource.endOfStream( ) : (( ) => {
                        sourceBuffer.timestampOffset = _duration - 2;
                        httpGet("/streamN.fmp4"); // next fmp4
                    })( );
                }
                https.open('get', url);
                https.send( );
            }
            sourceBuffer.onupdateend = _evt =>
                completeFile && completeFile(mediaSource.duration);
            httpGet("/stream0.fmp4"); // initial fmp4
        }
        video.width    = width;
        video.height   = height;
        video.muted    = true;
        video.controls = "controls";
        video.autoplay = "autoplay";
        video.src = URL.createObjectURL(mediaSource);
        document.body.append(video);
    }
};
new HttpPlayer(1024, 768);
</script></body></html>

沒有留言:

張貼留言

使用 pcie 轉接器連接 nvme SSD

之前 AM4 主機板使用 pcie ssd, 但主機板故障了沒辦法上網, 只好翻出以前買的 FM2 舊主機板, 想辦法讓老主機復活, 但舊主機板沒有 nvme 的界面, 因此上網買了 pcie 轉接器用來連接 nvme ssd, 遺憾的是 grub2 bootloader 無法識...