0

I am creating a music streaming service using the MEAN stack. So far, I have written code that uploads an mp3 file to my MongoDB database, using GridFS, and I can also download that file to the root folder of my site.

However, I do not want the download stream to write to a file, rather stream to a player/the speakers so that the file is not on the user's system, simply streams from the server.

I have been looking at the npm speaker module, and have attempted to implement it as below:

var assert = require('assert');
var fs = require('fs');
var mongodb = require('mongodb');
var Speaker = require('speaker');

var uri = 'mongodb://localhost:27017/test';

var speaker = new Speaker({
    channels: 2,          // 2 channels
    bitDepth: 16,         // 16-bit samples
    sampleRate: 44100     // 44,100 Hz sample rate
});

mongodb.MongoClient.connect(uri, function(error, db) {
    assert.ifError(error);

    var bucket = new mongodb.GridFSBucket(db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
    });

    bucket.openDownloadStreamByName('testmp3.mp3').pipe(speaker)


});

I'm not sure if I need to implement a buffer to do this. The npm speaker moudule, as far as I am aware, is a writable stream, and so I should be able to pipe to it.

The solution I have above, produces about 30 seconds of static noise, before quitting with the "Process finished with exit code 132 (interrupted by signal 4: SIGILL)" error.

I am new to NodeJS etc so any help on this would be very much appreciated.

Thanks

1 Answers1

0

You need a decoder to decode mp3 files.

const lame = require('lame');
// create the Encoder instance
let decoder = new lame.Decoder({
    // pcm output
    channels: 2,        // 2 channels (left and right)
    bitDepth: 16,       // 16-bit samples
    sampleRate: 44100,  // 44,100 Hz sample rate

    // mp3 input
    bitRate: 128,
    outSampleRate: 44100,
    mode: lame.STEREO // STEREO (default), JOINTSTEREO, DUALCHANNEL or MONO
});


// Create the Speaker instance
let speaker = new Speaker({
    channels: 2,          // 2 channels
    bitDepth: 16,         // 16-bit samples
    sampleRate: 44100     // 44,100 Hz sample rate
});

bucket.openDownloadStreamByName('testmp3.mp3').pipe(decoder);
decoder.pipe(speaker);
Ashok Kumar Sahoo
  • 580
  • 3
  • 8
  • 24