在 Node.js 应用程序中使用
fluent-ffmpeg
来截断和流式传输 MP3 音频文件时,我遇到了反复出现的问题。当我直接将输出写入文件时,该过程完美运行,但是当我尝试将输出作为流处理以收集缓冲区中的数据时,fluent-ffmpeg
会抛出错误,指出 MP3 输出格式不可用。
要点:
libmp3lame 编码器肯定包含在我的 FFmpeg 安装中。 仅当尝试通过流收集缓冲区中已处理的输出时,才会出现此问题。 我尝试使用 .format('mp3') 显式设置格式,但问题仍然存在。 直接在命令行中使用相同的参数运行 FFmpeg 可以正常工作,不会出现任何错误,这表明该问题可能与 Fluent-ffmpeg 处理流输出的方式有关。
这是导致问题的代码片段:
import { PassThrough } from 'stream';
import ffmpeg from 'fluent-ffmpeg';
import fs from 'fs';
function truncateAudioStream(inputStream, duration) {
return new Promise((resolve, reject) => {
let audioBuffer = Buffer.from([]);
const passThrough = new PassThrough();
ffmpeg(inputStream)
.setFfmpegPath('C:\\Program Files\\FFmpeg\\bin\\ffmpeg.exe')
.audioCodec('libmp3lame')
.setDuration(duration)
.on('end', () => resolve(audioBuffer))
.on('error', reject)
.on('data', (chunk) => {
audioBuffer = Buffer.concat([audioBuffer, chunk]);
})
.pipe(passThrough);
});
}
const inputAudioPath = 'path/to/input.mp3';
const inputStream = fs.createReadStream(inputAudioPath);
truncateAudioStream(inputStream, 25)
.then((truncatedAudioBuffer) => {
// Handling the buffer
})
.catch((error) => {
console.error('Error truncating audio stream:', error);
});
The error output is as follows:
Error truncating audio stream: Error: Output format mp3 is not available
at C:\path\to\fluent-ffmpeg\lib\capabilities.js:589:21
...