6

How to loop an MP3?

I use this to play an MP3, but it only plays once.

I want to play the MP3 continuously.

/*jslint node: true, vars: true, maxerr: 50, indent: 4 */
(function (console, require, alarm) {
    "use strict";

    var fs = require("fs");
    var lame = require("lame");
    var Speaker = require("speaker");

    function start() {
        var stream = fs.createReadStream("sounds/alarm.mp3");
        stream.pipe(new lame.Decoder()).pipe(new Speaker());
    }

    alarm.start = start;
}(global.console, require, exports));

Using:

XP1
  • 6,910
  • 8
  • 54
  • 61
  • Document what you have researched. Couldn't find anything in node documentation for lame? speaker? etc. – djechlin May 24 '13 at 21:59
  • I am not sure what is the right way to do it. I have tried `stream.on("close", function () { start(); });`, but that did not work. It started playing several MP3s simultaneously and then stopped. – XP1 May 24 '13 at 22:13
  • I have tried saving the Decoder and Speaker instances into variables and then modifying the line to `stream.pipe(decoder, {end: false}).pipe(speaker, {end: false});`. This causes Node to eat all the memory and then crash: "FATAL ERROR: Evacuation Allocation failed - process out of memory". – XP1 May 24 '13 at 22:31
  • I've upvoted your question but I recommend including your last two comments in it, instead of in comment. – djechlin May 24 '13 at 22:33

1 Answers1

2

Wait for the Speaker instance's "finish" event before starting up a new instance.

var speaker = new Speaker();
speaker.on('finish', start);
stream.pipe(new lame.Decoder()).pipe(speaker);
TooTallNate
  • 1,477
  • 3
  • 20
  • 41
  • I replaced the second line in `start` with your three lines, but it only plays once. It seems that the "finish" event never fires. I am using node-lame 1.0.2, node-speaker 0.0.10, and Node 0.10.8 on Windows 8. – XP1 May 25 '13 at 00:05