我正在 node js 上开发 FFMPEG。我想使用 Node js 从视频文件中检索音轨。我也想保存这样的文件,但我不知道如何保存。
我认为这行代码对我有帮助:
ffmpeg('/path/to/file.avi').noVideo();
我在 npm 包中得到了这个。我不太明白如何使用它以及如何实际保存音频文件。
发挥作用的其他一些代码行:
try {
var process = new ffmpeg('/path/to/your_movie.avi');
process.then(function (video) {
// Callback mode
video.fnExtractSoundToMP3('/path/to/your_audio_file.mp3', function (error, file) {
if (!error)
console.log('Audio file: ' + file);
});
}, function (err) {
console.log('Error: ' + err);
});
} catch (e) {
console.log(e.code);
console.log(e.msg);
}
我的问题是:
如何从 FFMPEG 视频中检索音频?如何保存?
最佳答案
我会这样做:
var ffmpeg = require('fluent-ffmpeg');
/**
* input - string, path of input file
* output - string, path of output file
* callback - function, node-style callback fn (error, result)
*/
function convert(input, output, callback) {
ffmpeg(input)
.output(output)
.on('end', function() {
console.log('conversion ended');
callback(null);
}).on('error', function(err){
console.log('error: ', e.code, e.msg);
callback(err);
}).run();
}
convert('./df.mp4', './output.mp3', function(err){
if(!err) {
console.log('conversion complete');
//...
}
});
只要确保 ffmpeg
已安装并且是系统路径的一部分,还要确保所有必要的代码都存在。
更新:
对于没有音频的视频,只需执行 .noAudio().videoCodec('copy')
:
function copyWitoutAudio(input, output, callback) {
ffmpeg(input)
.output(output)
.noAudio().videoCodec('copy')
.on('end', function() {
console.log('conversion ended');
callback(null);
}).on('error', function(err){
console.log('error: ', err);
callback(err);
}).run();
}
更新 2:
将视频和音频合并为一个:
function mergeMedia(aud, vid, output, callback) {
ffmpeg()
.input(aud)
.input(vid)
.output(output)
.outputOptions(
'-strict', '-2',
'-map', '0:0',
'-map', '1:0'
).on('end', function() {
console.log('conversion ended');
callback(null);
}).on('error', function(err){
console.log('error: ', err);
callback(err);
}).run();
}
关于javascript - 视频到音频文件转换并通过 node js 中的 FFMPEG 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30842316/