首页 > 解决方案 > 如何注入nodejs流

问题描述

我有以下脚本它可以工作,但是我无法找出最佳解决方案,即当触发元数据标签时,它是停止/暂停流播放 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');

标签: node.jsbuffermp3icecast

解决方案


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

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

作为额外的好处,您不会被特定的编解码器和比特率束缚,并且可以为您的听众提供适当的选择。您也不必担心 MPEG 帧的时间安排,因为您的最终流可以是样本精确的。


推荐阅读