我想将youtube url转换为mp3文件。目前,我使用node的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文件的位置,而是传递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'
)
这是一个相对古老的问题,但可能会在未来对某人有所帮助——我自己在寻找类似的解决方案时偶然发现了这个问题,可以将youtube视频下载为mp3,而无需将文件保存在服务器上。我基本上决定直接将转换转换为响应,并按照我的期望进行工作。
最初在另一个线程中回答了这个问题:通过节点js 的ffmpeg mp3流
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');
});
};