3

I have two PCM-streams (decoder1 + decoder2):

var readable1 = fs.createReadStream("track1.mp3");
var decoder1 = new lame.Decoder({
    channels: 2,
    mode: lame.STEREO
});
readable1.pipe(decoder1);

and

var readable2 = fs.createReadStream("track2.mp3");
var decoder2 = new lame.Decoder({
    channels: 2,
    mode: lame.STEREO
});
readable2.pipe(decoder2);

Now I want to pipe the streams into one mix-function, where I can use the buffer-function like:

function mixStream(buf1, buf2, callback) {
    // The mixStream-Function is not implemented yet (dummy)
    var out = new Buffer(buf1.length);
    for (i = 0; i < buf1.length; i+=2) {
        var uint = Math.floor(.5 * buf1.readInt16LE(i));
        out.writeInt16LE(uint, i);
    }

    this.push(out);
    callback();
}

I need something like

mixStream(decoder1.pipe(), decoder2.pipe(), function() { }).pipe(new Speaker());

for output to speaker. Is this possible?

Franky
  • 709
  • 1
  • 5
  • 14

1 Answers1

2

Well, pipe() function actually means a stream is linked to another, a readable to a writable, for instance. This 'linking' process is to write() to the writable stream once any data chunk is ready on the readable stream, along with a little more complex logic like pause() and resume(), to deal with the backpressure.

So all you have to do is to create a pipe-like function, to process two readable streams at the same time, which drains data from stream1 and stream2, and once the data is ready, write them to the destination writable stream.

I'd strongly recommend you to go through Node.js docs for Stream.

Hope this is what you are looking for :)

YLS
  • 697
  • 5
  • 9
  • Sorry, I am extremely not very familiar with PCM streams etc. What I don't understand mostly is how to merge the two streams into one output stream -- which I thought this question was asking hence why I put the bounty on it. – FireController1847 Jul 03 '18 at 03:10
  • I am not very familiar with PCM but if you are considering merging two streams into one, I'd be glad to provide further help, but maybe you got time for the docs first? BTW, if you are trying to overlay two tracks into a single audio file. I'd recommend this https://stackoverflow.com/questions/14498539/how-to-overlay-two-audio-files-using-ffmpeg . You can simply use child_process to spawn the ffmpeg to do the job. – YLS Jul 03 '18 at 03:17
  • I thought I understood streams pretty well but obviously not enough haha. Just as you commented this I was searching up basics for PCM streams in Node.js, hopefully I'll get something out of it. – FireController1847 Jul 03 '18 at 03:18