Audio on the Raspberry Pi with Node.js

I recently wanted to play some audio through the Raspberry Pi programatically, but primarily being a web developer I wasn’t really sure how to approach the task. I can manipulate the DOM all day without breaking a sweat, but without the Web Audio API or <audio> element I was a bit stumped. Previously I’ve played around with Node.js on the Pi, but I didn’t think it would have any packages for audio and thought I’d have to use Python or Scratch which are well supported on the Pi.

Turns out you can use Node and it’s pretty simple too. I based my implementation on this Gist:

If you’re not familiar with Node, I’ll explain a little about what this does. The first few lines are importing all the modules we’ll need: fs the filesystem module baked into Node, which will read in the MP3. Next lame which will decode the MP3 into raw PCM data. Finally speaker that simply outputs PCM audio data you feed it.

In this example the file is passed to Node as an argument when the script is run from the command line, like so:

$ node mp3player.js sounds/file.mp3

The MP3 is piped through lame and then as it is decoded output to speaker. This worked right out of the box on my Mac, but a bit of fiddling was required to get it working on the Pi.

First lame needed to compile a bunch of native extensions for the MP3 decoding, this wasn’t really a problem as it compiled cleanly the first time, it just took a while.

Second, the program ran without error, but I couldn’t hear anything. Turns out the Pi can output audio over HDMI or the 3.5mm stereo jack, but in my case it was sending the audio over HDMI, even though the monitor connected didn’t have speakers. Fortunately you can override the output and the following command will switch it to the stereo jack:

$ amixer cset numid=3 1

After that it worked a treat, playing crisp and clear sound.

I didn’t realise it at the time, but I’ve just noticed that the Gist and modules are all by Nathan Rajlich, nice work!

This is awesome! I was having trouble installing “speaker” on my raspberry pi. I searched for some answers and it looks like you need to install libasound2-dev with apt-get first. then ‘speaker’ installed just fine.

Hello, this post really is helpful! But I’m having problem installing lame on my raspberry pi.
I installed it but when adjusting, it says that it can’t find the directory..
Can you help me..?TT