问题描述
我创建了一个简单的服务器,它使用 fs 模块将 mp3 文件流式传输到浏览器,浏览器在 html5 音频元素中播放它.事实上,音频流非常好,但是,即使我寻求的部分已经被缓冲,我也无法通过流进行搜索.
I have created a simple server that uses the fs module to stream an mp3 file to a browser which plays it in an html5 audio element. As it is, the audio streams perfectly fine, however, I can't seek through the stream, even if the part I seek to has already been buffered.
var express = require('express');
var app = express();
var fs = require('fs');
app.get('/', function (req, res) {
var filePath = 'music.mp3';
var stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size,
});
var readStream = fs.createReadStream(filePath);
readStream.pipe(res);
});
其他类似的 Q&As 建议添加 Content-Range 标头,但我找不到如何执行此操作的简单示例.其他人说使用 206 Partial-Content 标头,但当我这样做时,音频根本不会播放.
Other similar Q&As have suggested to add the Content-Range header, but I can't find a simple example of how to do that. Others have said to use the 206 Partial-Content header, but when I do that the audio won't play at all.
这是一个 演示(在 Windows 上的 chrome 上测试)
Here's a demo (testing on chrome on windows)
推荐答案
根据 这个问题:
var express = require('express'),
fs = require('fs'),
app = express()
app.get('/', function (req, res) {
var filePath = 'music.mp3';
var stat = fs.statSync(filePath);
var total = stat.size;
if (req.headers.range) {
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;
var readStream = fs.createReadStream(filePath, {start: start, end: end});
res.writeHead(206, {
'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
'Accept-Ranges': 'bytes', 'Content-Length': chunksize,
'Content-Type': 'audio/mpeg'
});
readStream.pipe(res);
} else {
res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'audio/mpeg' });
fs.createReadStream(filePath).pipe(res);
}
});
这篇关于节点 - 无法寻找音频流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!