Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play audio with Node.JS

Tags:

node.js

audio

I'm currently using child_process and command-line mplayer to play audio on the local machine, with my Node.JS application. This works, but it's not really an excellent solution. My biggest issue is that it takes 500ms from mplayer is started to audio starts playing.

Are there better ways to play audio? Preferably compressed audio, but I'll take what I can get.

like image 806
Znarkus Avatar asked Sep 22 '12 11:09

Znarkus


People also ask

CAN node JS play audio?

To play a sound in our Node. js code, we will use an NPM package called (perhaps not surprisingly) play-sound. This package works with a number of different command-line audio players including: mplayer.

How do I play a sound in JavaScript?

play() to Play Audio Files in JavaScript. We can load an audio file in JavaScript simply by creating an audio object instance, i.e. using new Audio() . After an audio file is loaded, we can play it using the . play() function.

Can JavaScript play WAV files?

Method 2: JavaScriptYou may also load a sound file with JavaScript, with new Audio() . const audio = new Audio("freejazz. wav"); You may then play back the sound with the .


2 Answers

I would suggest using node-speaker, which outputs raw PCM data to your speakers (so basically, it plays audio).

If you're playing something like mp3 files you might need to decode it first to PCM data, which is exactly what node-lame does.

Hope that helps.

like image 171
pedromtavares Avatar answered Oct 13 '22 18:10

pedromtavares


Simplest I've found (on Mac OS) is to use

exec('afplay whatever.mp3', audioEndCallback) 
like image 28
lipsumar Avatar answered Oct 13 '22 18:10

lipsumar