node.js:如何管道 - youtube到mp4到mp3

时间:2013-08-11 03:23:00

标签: node.js stream pipe

我想将youtube网址转换为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块时进行转换?

3 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:0)

这是一个相对古老的问题,但未来可能有所帮助 - 我在寻找类似的解决方案下载youtube vid作为mp3而无需将文件保存在服务器上时自己偶然发现了。我基本上决定将转换直接用于响应,并且正如我所希望的那样工作。

最初在另一个帖子中回答了这个问题:ffmpeg mp3 streaming via node js

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

};

答案 2 :(得分:-1)

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

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