我正在试验 Chrome 中可用的新 MediaSource API。
我正在尝试将二进制数据从 WebSocket 动态附加到视频媒体源。
从https://html5-demos.appspot.com/static/media-source.html的示例开始,我的代码目前是:
var websocket = new WebSocket('ws://localhost:8080');
websocket.binaryType = 'arraybuffer';
var mediaSource = new MediaSource();
var buffer;
var queue = [];
var video = $('.video')[0];
video.src = window.URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', function(e) {
video.play();
buffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.64001E"');
buffer.addEventListener('updatestart', function(e) { console.log('updatestart: ' + mediaSource.readyState); });
buffer.addEventListener('update', function(e) { console.log('update: ' + mediaSource.readyState); });
buffer.addEventListener('updateend', function(e) { console.log('updateend: ' + mediaSource.readyState); });
buffer.addEventListener('error', function(e) { console.log('error: ' + mediaSource.readyState); });
buffer.addEventListener('abort', function(e) { console.log('abort: ' + mediaSource.readyState); });
buffer.addEventListener('update', function() { // Note: Have tried 'updateend'
if (queue.length > 0 && !buffer.updating) {
buffer.appendBuffer(queue.shift());
}
});
}, false);
mediaSource.addEventListener('sourceopen', function(e) { console.log('sourceopen: ' + mediaSource.readyState); });
mediaSource.addEventListener('sourceended', function(e) { console.log('sourceended: ' + mediaSource.readyState); });
mediaSource.addEventListener('sourceclose', function(e) { console.log('sourceclose: ' + mediaSource.readyState); });
mediaSource.addEventListener('error', function(e) { console.log('error: ' + mediaSource.readyState); });
websocket.addEventListener('message', function(e) {
if (typeof e.data !== 'string') {
if (buffer.updating || queue.length > 0) {
queue.push(e.data);
} else {
buffer.appendBuffer(e.data);
}
}
}, false);
我一直收到错误消息:InvalidStateError: Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer has been removed from the parent media source.
在一个附加之后。看起来 MediaSource 在调用 后立即关闭buffer.appendData()
。
有什么方法可以优雅地做到这一点?
注意: chrome://media-internals/ 不返回任何有用的信息。