5

I'm trying to play some mp3 files in node.js. The thing is that I manage to play them one by one, or even, as I want in parallel. But what I also want is to be able to control the amplitude (gain) to be able to create a crossfade in the end. Could anyone help me understand what it is I need to do? (I want to use it in node-webkit so I need a solution that is node.js based with no external dependencies.)

This is what I've got so far:

var lame = require('lame'), Speaker = require('speaker'), fs = require('fs');
var audioOptions = {channels: 2, bitDepth: 16, sampleRate: 44100};
var decoder = lame.Decoder();


var stream = fs.createReadStream("music/ge.mp3", audioOptions).pipe(decoder).on("format", function (format) {
  this.pipe(new Speaker(format))
}).on("data", function (data) {
  console.log(data)
})
jonepatr
  • 7,769
  • 7
  • 30
  • 53

1 Answers1

0

I customized the npm package pcm-volume to do that. To crossfade, provide two pcm audio buffers (output of your decoders). Pipe the result to your Speaker object.

Here is the main part of the modifications. In this case the crossfade happens at the scale of the provided buffer, but you can change that.

var l = buf.length;
var out = new Buffer(l);

for (var i=0; i < l; i+=2) {
    volumeSunrise = 0.5*this.volume*(1-Math.cos(pi*i/l));
    volumeSunset  = 0.5*this.volume*(1+Math.cos(pi*i/l));
    uint = Math.round(volumeSunrise*buf.readInt16LE(i) + volumeSunset*this.sunsetBuffer.readInt16LE(i));
    // you may want to ensure that -32767 <= uint <= 32768 here, in case you use a volume higher than 1
    out.writeInt16LE(uint, i);
}

this.push(out);
callback()
astooooooo
  • 362
  • 2
  • 13