我想将视频文件发送到客户端并使用.createObjectURL()显示视频。
节点server.js:
var fs = require("fs"),
http = require("http");
http.createServer(function (req, res) {
if (req.url == "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end('<video id="video" src="" autoplay controls loop width="200px" height="200px" muted></video>' +
'<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>' +
'<script src="blobvideo.js"></script>');
}
else if (req.url == "/blobvideo.js") {
res.writeHead(200, { "Content-Type": "application/javascript" });
fs.readFile('./blobvideo.js', function(err, data) {
res.end(data.toString());
});
}
else if (req.url == "/video") {
fs.readFile('video.mp4', function(err, data) {
res.end(data);
});
}
}).listen(3000);
客户端blobvideo.js:
$.ajax( "/video" ).done(function(data) {
var ab = new ArrayBuffer(data.length);
var view = new Uint8Array(ab);
for(var i = 0; i < data.length; ++i) {
view[i] = data[i];
}
blob = new Blob([ab], { type: "video/mp4" });
document.getElementById("video").src = (window.URL || window.webkitURL).createObjectURL(blob);
});
在此代码中,视频全部一起发送,视频无法播放。我的问题:
如何解决这个问题才能播放视频?
如何更改它以流式传输文件而不是等待整个视频下载?
编辑澄清
我想在客户端上使用Blob
和.createObjectURL()
,因为我正在尝试构建WebRTC RTCPeerConnection的点对点视频实现,以便可以从中发送静态视频数据客户端到另一个客户端而不通过服务器发送。
答案 0 :(得分:0)
我只是将video.mp4作为静态资源投放,并将视频元素的src
设置为该视频的网址。
答案 1 :(得分:0)
这是纯粹的nodejs javascript,可以在没有外部库依赖性的情况下传输视频/音频,并且不需要客户端代码...使用以下命令启动它:
node this_code.js
然后将您的客户端浏览器指向
http://localhost:8888
巨大的好处是浏览器客户端视频呈现UI小部件正常工作 - (能够跳转到某个随机媒体位置等)
var http = require('http'),
fs = require('fs'),
util = require('util');
// put any audio or video file here
var path = "/path/to/audio/or/video/file/local/to/server/cool.mp4";
var port = 8888;
var host = "localhost";
http.createServer(function (req, res) {
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers.range) {
// meaning client (browser) has moved the forward/back slider
// which has sent this request back to this server logic ... cool
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1;
var chunksize = (end-start)+1;
console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
file.pipe(res);
} else {
console.log('ALL: ' + total);
res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'video/mp4' });
fs.createReadStream(path).pipe(res);
}
}).listen(port, host);
console.log("Server running at http://" + host + ":" + port + "/");
享受,