我正在尝试使用node.js设置一个支持将视频流式传输到HTML5视频标签的网络服务器.到目前为止,这是我的代码:
var range = request.headers.range;
var total = file.length;
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;
response.writeHead(206, { "Content-Range": "bytes " + start + "-" + end + "/" + total, "Accept-Ranges": "bytes", "Content-Length": chunksize, "Content-Type": type });
response.end(file);
Run Code Online (Sandbox Code Playgroud)
其中"request"表示http请求,type是"application/ogg"或"video/ogg"(我已尝试过两者),"file"是从文件系统中读取的.ogv文件.以下是响应标头:
Content-Range bytes 0-14270463/14270464
Accept-Ranges bytes
Content-Length 14270464
Connection keep-alive
Content-Type video/ogg
Run Code Online (Sandbox Code Playgroud)
我已经检查了响应标头,这段代码看起来运行正常,但是有一些问题:
我有一个 PHP 脚本,用于从 URL 流式传输视频,并且我想花时间来控制流。
当在视频中跳转时,浏览器会发出一系列字节的 HTTP 请求。
请求标头
Accept:*/ *
Accept-Encoding:identity;q=1, *;q=0
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:h.com
If-Range:Tue, 20 Oct 2015 23:38:00 GMT
Range:bytes=560855038-583155711
Referer:http://h.com/7743a76d2911cdd90354bc42be302c6946c6e5b4
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36
Run Code Online (Sandbox Code Playgroud)
响应头
Accept-Ranges:bytes
Cache-Control:private, max-age=14400
Connection:Keep-Alive
Content-Length:22300674
Content-Range:bytes 560855038-583155711/605162520
Content-Type:video/mp4
Date:Tue, 10 May 2016 11:23:34 GMT
Expires:Tue, 10 05 2016 15:23:34 GMT
Keep-Alive:timeout=5, max=98
Last-Modified:Tue, 20 Oct 2015 23:38:00 GMT
Server:Apache/2.4.7 (Ubuntu)
X-Powered-By:PHP/5.5.9-1ubuntu4.16
Run Code Online (Sandbox Code Playgroud)
时间到字节的转换如何进行?
在我的 PHP 服务器上,我尝试从字节请求中获取时间:
$time_second = $start_request_byte / $video_size_byte * $video_length_second;
Run Code Online (Sandbox Code Playgroud)
但这不是解决方案,它不准确......有什么想法吗?
谢谢
我有一个小型快速服务器,可以下载或流式传输 mp3 文件,如下所示:
const express = require('express');
const fs = require('fs');
const app = express();
app.use('/mp3', express.static(__dirname + '/mp3'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/stream', (req, res) => {
const file = __dirname + '/mp3/trololol.mp3';
fs.exists(file, (exists) => {
if (exists) {
const rstream = fs.createReadStream(file);
rstream.pipe(res);
} else {
res.send('Error - 404');
res.end();
}
});
});
app.get('/download', (req, res) => {
const file = __dirname + '/mp3/trololol.mp3';
res.download(file);
});
app.listen(3000, () => console.log('Example app listening …Run Code Online (Sandbox Code Playgroud)