node.js:如何pipe道 – YouTube的MP4到MP3

我想将YouTubeurl转换为MP3文件。 目前,我使用节点的ytdl模块下载mp4,如下所示:

fs = require 'fs' ytdl = require 'ytdl' url = 'http://www.youtube.com/watch?v=v8bOTvg-iaU' mp4 = './video.mp4' ytdl(url).pipe(fs.createWriteStream(mp4)) 

下载完成后,我使用fluent-ffmpeg模块将mp4转换为mp3,如下所示:

 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' ) 

我不想在开始mp3转换之前保存整个mp4。 如何将mp4传输到proc,以便在接收mp4块时执行转换?

而不是传递mp4文件的位置,请传递ytdlstream作为源,如下所示:

 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' ) 

这对我不起作用。 如果我设置了一个本地的.mp4文件,但是使用stream,则代码如下。

 var ytUrl = 'http://www.youtube.com/watch?v=' + data.videoId; var stream = youtubedl(ytUrl, { quality: 'highest' }); var saveLocation = './mp3/' + data.videoId + '.mp3'; var proc = new ffmpeg({ source: './mp3/test.mp4' //using 'stream' does not work }) .withAudioCodec('libmp3lame') .toFormat('mp3') .saveToFile(saveLocation, function(stdout, stderr) { console.log('file has been converted succesfully'); }); 

这是一个相对古老的问题,但可能会帮助未来的人 – 当我寻找一个类似的解决scheme,下载一个YouTube的video无需保存在服务器上的文件,我自己偶然发现。 我基本上决定把转换直接转化为回应,而且正如我所希望的那样工作。

最初在不同的线程回答这个问题: 通过节点js的ffmpeg mp3stream

 module.exports.toMp3 = function(req, res, next){ var id = req.params.id; // extra param from front end var title = req.params.title; // extra param from front end var url = 'https://www.youtube.com/watch?v=' + id; var stream = youtubedl(url); //include youtbedl ... var youtubedl = require('ytdl'); //set response headers res.setHeader('Content-disposition', 'attachment; filename=' + title + '.mp3'); res.setHeader('Content-type', 'audio/mpeg'); //set stream for conversion var proc = new ffmpeg({source: stream}); //currently have ffmpeg stored directly on the server, and ffmpegLocation is the path to its location... perhaps not ideal, but what I'm currently settled on. And then sending output directly to response. proc.setFfmpegPath(ffmpegLocation); proc.withAudioCodec('libmp3lame') .toFormat('mp3') .output(res) .run(); proc.on('end', function() { console.log('finished'); }); 

};