我使用Node.js通过Websocket将实时webm视频流式传输到一个网页,该网页将在标签中播放它。以下是来自服务器和客户端的代码:
服务器:var io = require('./libs/socket.io').listen(8080, {log:false});
var fs = require('fs');
io.sockets.on('connection', function (socket)
{
console.log('sono entrato in connection');
var readStream = fs.createReadStream("video.webm");
socket.on('VIDEO_STREAM_REQ', function (req)
{
console.log(req);
readStream.addListener('data', function(data)
{
socket.emit('VS',data);
});
});
});
客户:<html>
<body>
<video id="v" autoplay> </video>
<script src='https://localhost/socket.io/socket.io.js'></script>
<script>
window.URL = window.URL || window.webkitURL;
window.MediaSource = window.MediaSource || window.WebKitMediaSource;
if(!!! window.MediaSource)
{
alert('MediaSource API is not available!');
return;
}
var mediaSource = new MediaSource();
var video = document.getElementById('v');
video.src = window.URL.createObjectURL(mediaSource);
mediaSource.addEventListener('webkitsourceopen', function(e)
{
var sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vorbis,vp8"');
var socket = io.connect('http://localhost:8080');
if(socket)
console.log('Library retrieved!');
socket.emit('VIDEO_STREAM_REQ','REQUEST');
socket.on('VS', function (data)
{
console.log(data);
sourceBuffer.append(data);
});
});
</script>
</body>
</html>
我使用Chrome 26,我得到这个错误:"未捕获的错误:InvalidAccessError: DOM异常15"。似乎提供给append方法的缓冲区类型是错误的。我已经尝试过在Blob, Array和Uint8Array中转换它,但没有运气。
您的示例只包含在这里呈现的页面上显示的代码:http://html5-demos.appspot.com/static/media-source.html
检查源代码,第155行是你缺少的:
var file = new Blob([uInt8Array], {type: 'video/webm'});
所以,你需要告诉Blob的内容类型,然后输入缓冲区Uint8Array(见第171行):
sourceBuffer.append(new Uint8Array(e.target.result));