tldr tldr - 3 months ago 119
Node.js Question

node.js : how to pipe - youtube to mp4 to mp3

I want to convert a youtube url into an mp3 file. Currently, I download the mp4 using node's ytdl module, like so:

fs = require 'fs'
ytdl = require 'ytdl'

url = 'http://www.youtube.com/watch?v=v8bOTvg-iaU'
mp4 = './video.mp4'

ytdl(url).pipe(fs.createWriteStream(mp4))


Once the download is complete, I convert the mp4 into mp3 using the fluent-ffmpeg module, like so:

ffmpeg = require 'fluent-ffmpeg'

mp4 = './video.mp4'
mp3 = './audio.mp3'

proc = new ffmpeg({source:mp4})
proc.setFfmpegPath('/Applications/ffmpeg')
proc.saveToFile(mp3, (stdout, stderr)->
return console.log stderr if err?
return console.log 'done'
)


I don't want to have to save the entire mp4 before starting the mp3 conversion. How do I pipe the mp4 into proc so it carries out the conversion as it receives the mp4 chunks?

Answer

Instead of passing the location of mp4 file, pass in the ytdl stream as the source, like so:

stream = ytdl(url)

proc = new ffmpeg({source:stream})
proc.setFfmpegPath('/Applications/ffmpeg')
proc.saveToFile(mp3, (stdout, stderr)->
            return console.log stderr if err?
            return console.log 'done'
        )