我正在运行一个节点服务器,我想从使用 WebTorrent(https://webtorrent.io/docs)的磁力链接流式传输视频。当我运行它时,即使我已将变量设置为 .mp4 文件,似乎也没有正确引用该文件。
为了清楚起见,我在此示例中添加了给定的 torrentID(磁力链接),以消除我在 express 和 URL 方面可能遇到的任何问题。此磁力链接可下载 MP4 格式的音乐视频。
视频播放器正在显示,但没有播放视频。我假设这意味着我没有尝试访问正确的文件。如果您需要了解更多关于 WebTorrent 的信息来帮助我,您可以在https://webtorrent.io/docs上阅读相关信息
var fs = require("fs"),
http = require("http"),
url = require("url"),
path = require("path"),
request = require('request'),
host = '127.0.0.1',
port = 3000,
express = require("express"),
app = express(),
server = http.createServer(app),
WebTorrent = require('webtorrent'),
client = new WebTorrent();
app.get('/streamvid/:magLink', function(req, res){
//var torrentID = req.params.magLink;
var torrentID = 'magnet:?xt=urn:btih:84123E8B4E850A796403736E0CF02E409F0EF00B';
client.add(torrentID, function (torrent) {
var file = torrent.files[0]
file.name = 'movie.mp4';
if (req.url != "/movie.mp4") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end('<video width="1024" height="768" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video>');
} else {
var range = req.headers.range;
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
fs.stat(file, function(err, stats) {
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
});
var stream = fs.createReadStream(file, { start: start, end: end })
.on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
res.end(err);
});
});
}
})
});
var server = http.createServer(app);
var server = app.listen(port, host);
server.on('error', function(err) {
console.log('error:' + err);
});
server.on('listening', function(){
console.log('Server is Up and Running');
});