如何注入Node.js流

时间:2019-11-08 07:22:36

标签: node.js buffer mp3 icecast

我有以下脚本可以工作,但是我想不出最好的解决方案:触发元数据标签时,它是停止/暂停流播放mp3 URL,然后重新连接到流(作为新连接) )。

我的第一个想法起作用了,但是,它似乎暂停了Icecast流,然后插入mp3,在播放之后,它只是从暂停的位置继续播放(这是不需要的)。我想要的是,如果mp3长2分钟,那么Icecast流也应该跳过2分钟。

var http = require('http'),request = require('request');
var url = 'http://stream.radiomedia.com.au:8003/stream'; // URL to a known Icecast stream


var icecast = require('icecast-stack');
var stream = icecast.createReadStream(url);

// var radio = require("radio-stream");
// var stream = radio.createReadStream(url);

var clients = [];

stream.on("connect", function() {
  console.error("Radio Stream connected!");
  //console.error(stream.headers);
});

// Fired after the HTTP response headers have been received.
stream.on('response', function(res) {
  console.error("Radio Stream response!");
  console.error(res.headers);
});


// When a chunk of data is received on the stream, push it to all connected clients
stream.on("data", function (chunk) {
    if (clients.length > 0){
        for (client in clients){
            clients[client].write(chunk);
        };
    }
});

// When a 'metadata' event happens, usually a new song is starting.
stream.on('metadata', function(metadata) {
  var title = icecast.parseMetadata(metadata).StreamTitle;
  console.error(title);

});


// Listen on a web port and respond with a chunked response header. 
var server = http.createServer(function(req, res){ 
    res.writeHead(200,{
        "Content-Type": "audio/mpeg",
        'Transfer-Encoding': 'chunked'
    });
    // Add the response to the clients array to receive streaming
    clients.push(res);
    console.log('Client connected; streaming'); 
});
server.listen("9000", "127.0.0.1");

console.log('Server running at http://127.0.0.1:9000');

1 个答案:

答案 0 :(得分:0)

您不能像这样简单地任意连接流。使用MP3,位存储库将咬住您。通常,这是一个小故障,但是您可以有更多挑剔的客户端,直接断开连接。

要执行您想做的事情,实际上您需要将所有内容解码为PCM,按您认为合适的方式混合音频,然后对新的流进行重新编码。

作为一项额外的奖励,您将不受特定编解码器和比特率的束缚,并且可以为收听者提供适当的选择范围。您也不必担心MPEG帧的时间安排,因为您的最终流可以精确到样本。