基本问题:在浏览器中显示H264实时流。
解决方案:让我们将其转换为碎片化的mp4,并通过websocket(或XHR(逐块加载到MSE中。
听起来太容易了。但是我想用纯JS在客户端进行碎片化。
所以我正在尝试使用MP4Box.js。在其自述页面上,它指出:它有一个演示:"执行即时碎片化的播放器"。
这就是我需要的东西!
但是,根本不调用应馈送 MSE 的 onSegment 回调:
var ws; //for websocket
var mp4box; //for fragmentation
function startVideo() {
mp4box = MP4Box.createFile();
mp4box.onError = function(e) {
console.log("mp4box failed to parse data.");
};
mp4box.onMoovStart = function () {
console.log("Starting to receive File Information");
};
mp4box.onReady = function(info) {
console.log(info.mime);
mp4box.onSegment = function (id, user, buffer, sampleNum) {
console.log("Received segment on track "+id+" for object "+user+" with a length of "+buffer.byteLength+",sampleNum="+sampleNum);
}
var options = { nbSamples: 1000 };
mp4box.setSegmentOptions(info.tracks[0].id, null, options); // I don't need user object this time
var initSegs = mp4box.initializeSegmentation();
mp4box.start();
};
ws = new WebSocket("ws://a_websocket_server_which_serves_h264_file");
ws.binaryType = "arraybuffer";
ws.onmessage = function (event) {
event.data.fileStart = 0; //tried also with event.data.byteOffset, but resulted error.
var nextBufferStart = mp4box.appendBuffer(event.data);
mp4box.flush(); //tried commenting out - unclear documentation!
};
}
window.onload = function() {
startVideo();
}
现在把它放到一个HTML文件中会导致JavaScript控制台中出现这种情况:
Starting to receive File Information
video/mp4; codecs="avc1.4d4028"; profiles="isom,iso2,avc1,iso6,mp41"
但之后什么也没发生。为什么这里不调用onSegment?(websocket服务器提供的h264文件可以在VLC中播放 - 但它不是碎片化的(
问题是以错误的方式使用nextBufferStart。
这应该是正确的:
var nextBufferStart = 0;
...
ws.onmessage = function (event) {
event.data.fileStart = nextBufferStart;
nextBufferStart = mp4box.appendBuffer(event.data);
mp4box.flush();
};