通过套接字将视频流传输到 html5 视频标签

2024-04-14

你好,我一直在尝试通过 socket.io 套接字将 webm 视频直接流式传输到 html5 视频标签。客户端和服务器端代码如下:

Server:

(function() {
    var Alert, Channel, Receiver, Takeover, express, pathLib;

    pathLib = require("path");
    fs = require("fs");
    express = require("express");

    module.exports = function(app, sockets) {
        router = express.Router();

        router.get("/clearAlerts", function(req, res) {
            console.log("reached!");
            return sockets.emit("alert-deleted");
        });

        router.get("/castVideo", function(req, res) {
            //move this to a better place
            console.log("reachedCastVideoss");
            var readStream = fs.createReadStream(pathLib.join(__dirname + "/../../../public/elephants-dream.webm"));
            readStream.addListener('data', function(data) {
                console.log("cast-video emitted");
                sockets.emit('cast-video', data);
            });
        });

        return app.use('/custom/', router);
    };

}).call(this);

Client:

 var socket = io.connect('http://localhost:4994');


window.URL = window.URL || window.webkitURL;
window.MediaSource = window.MediaSource || window.WebKitMediaSource;

var mediaSource = new MediaSource();
var video = document.getElementById("video");
var queue = [];
var sourceBuffer;
var firstChunk = true;

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

streamIt = function(e) {
    video.pause();
    mediaSource.addSourceBuffer('video/webm; codecs="vorbis,vp8"');
    mediaSource.sourceBuffers[0].addEventListener('updateend', onBufferUpdated);

    socket.on("cast-video", function(data) {
        console.log("appending to buffer");
        var uIntArray = new Uint8Array(data);

        if (firstChunk) {
            mediaSource.sourceBuffers[0].appendBuffer(uIntArray);
            firstChunk = false;
        }

        queue.push(uIntArray);
        if (queue.length === 33) {
            //mediaSource.endOfStream();
        }
    });

    var onBufferUpdated = function() {
        if (queue.length) {
            mediaSource.sourceBuffers[0].appendBuffer(queue.shift());
        }
    };
};


mediaSource.addEventListener('sourceopen', streamIt);
mediaSource.addEventListener('webkitsourceopen', streamIt);

当我尝试运行此代码时,似乎附加了流的第一个块 到 sourceBuffer,我可以看到我尝试播放的视频文件的第一帧(标题和 url),但仅此而已。看来只有第一次调用appendBuffer有效。我在某处读到了有关视频播放所需的初始化段的内容,但我也看到了一个不使用此初始化段的工作示例,所以我有点困惑。(链接到示例 http://html5-demos.appspot.com/static/media-source.html) 谁能澄清我是否真的需要这个初始部分?如果这样做,我如何检索该段的字节范围?或者如果我不需要这个段,我的代码有什么问题?谢谢。

今天多尝试一点,我发现如果我使用来自http://html5-demos.appspot.com/static/media-source.html http://html5-demos.appspot.com/static/media-source.html,这段代码确实有效。当我尝试使用来自的文件时http://www.webmfiles.org/demo-files http://www.webmfiles.org/demo-files,代码不起作用。我不知道为什么。


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过套接字将视频流传输到 html5 视频标签 的相关文章

随机推荐