我正试图从node.js服务器流式传输mp3,但我无法接收任何数据,或者,如果我刷新客户端页面,我会收到一个跨原点错误
我的服务器代码是:
fs.readFile(path, function(error, file) {
if (error) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error + "n");
response.end();
} else {
console.log('file ok');
var stat = fs.statSync(path);
var total = stat.size;
console.log('video size: ' + total);
var origin = (request.headers.origin || "*");
if (request.headers['range']) {
var range = request.headers.range;
console.log('range: ' + range);
var parts = range.replace(/bytes=/, "").split("-");
console.log('parts: ' + parts);
var partialstart = parts[0];
console.log('partialstart: ' + partialstart);
var partialend = parts[1];
console.log('partialend: ' + partialend);
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 fileStr = fs.createReadStream(path, {start: start, end: end});
response.writeHead(
"200",
"OK",
{
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": origin,
"Content-Type": 'audio/mp3',
"Access-Control-Max-Age": 60*60*24*365, // Seconds.
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE",
"Access-Control-Allow-Headers": "Content-Type",
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize
}
);
//response.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'audio/mpeg' });
fileStr.pipe(response);
} else {
console.log('ALL: ' + total);
response.writeHead(
"200",
"OK",
{
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": origin,
"Content-Type": "audio/mp3",
"Content-Length": file.length,
"Access-Control-Max-Age": 60*60*24*365, // Seconds.
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE",
"Access-Control-Allow-Headers": "Content-Type"
}
);
fs.createReadStream(path).pipe(response);
//response.end(html);
response.end(html);
console.log('-end-');
}
}
});
我总是到达目的地,但没有数据到达客户端。。
节点的媒体流模块。JS和JXcore。。https://github.com/obastemur/mediaserver
您可以使用它,也可以检查源代码。