gpt4 book ai didi

javascript - 如何从node.js获取音频流?

转载 作者:太空宇宙 更新时间:2023-11-04 02:58:30 25 4
gpt4 key购买 nike

我正在尝试从 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-');
}
}
});

我总是到达-end-,但没有数据到达客户端..

最佳答案

node.JS 和 JXcore 的媒体流模块.. https://github.com/obastemur/mediaserver

您可以使用它或查看源代码。

关于javascript - 如何从node.js获取音频流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23385098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com