1. 前端的HTML页面中直接写视频的地址,虽然可以播放,但是视频的进度条将无法工作。
<div class="watcht" > <video id="player" width="620" height="452" controls> <source src="/vedio/1-2.mp4" type="video/mp4"> </video> </div>
2. 后端需接受前端播放视频时的GET请求,并回复对应的请求头。
var file = path.resolve(__dirname, "../vedio/1-2.mp4"); fs.stat(file, function (err, stats) { if (err) { res.end(err); } var range = req.headers.range; var positions = range.replace(/bytes=/, "").split("-"); var start = parseInt(positions[0], 10); 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" });
3. 发送请求头后需创建文件流,发出请求的视频文件
var stream = fs.createReadStream(file, {start: start, end: end}) .on("open", function () { stream.pipe(res); }).on("error", function (err) { res.end(err); });