14

我想将 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 块时执行转换?

4

3 回答 3

13

不要传递 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'
        )
于 2013-08-11T04:17:40.207 回答
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 the output directly to the response.
    proc.setFfmpegPath(ffmpegLocation);
    proc.withAudioCodec('libmp3lame')
        .toFormat('mp3')
        .output(res)
        .run();
    proc.on('end', function() {
        console.log('finished');
    });
};
于 2016-08-21T04:49:42.153 回答
-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');
            });
于 2014-01-22T17:00:30.757 回答