使用ffmpeg将.mov流转为.flv时生成0KB无效文件的问题
Great question—this is a common gotcha when working with streams in fluent-ffmpeg. Let’s break down why your first code fails and how to fix it.
Root Cause
When you pass a file path to ffmpeg(), the library can automatically probe the file to detect its format, codecs, and other metadata. This lets ffmpeg properly decode the input without extra configuration.
But when you pass a ReadStream, ffmpeg can’t perform this upfront probing because streams are not seekable (it can’t jump around to read metadata headers like it can with a file). Without knowing the input format, ffmpeg doesn’t know how to decode the stream, so it doesn’t produce any output—hence the 0KB file. Additionally, using .pipe() directly with a stream input might not correctly trigger the ffmpeg processing workflow.
Fix: Explicitly Define Input Format and Use Proper Output Handling
To make the stream approach work, you need to:
- Tell ffmpeg exactly what format the input stream is in.
- Use fluent-ffmpeg’s built-in output methods to ensure the processing runs correctly.
Here’s the corrected code:
var ffmpeg = require('fluent-ffmpeg'); var fs = require('fs'); var writeStream = fs.createWriteStream('output.flv'); var readStream = fs.createReadStream('video.mov'); ffmpeg(readStream) .inputFormat('mov') // Explicitly set input format (matches your source file) .format('flv') // Set output format .output(writeStream) .on('end', () => console.log('Conversion finished successfully!')) .on('error', (err) => console.error('Conversion failed:', err)) .run(); // Trigger the ffmpeg process
Why This Works
inputFormat('mov'): Gives ffmpeg the critical info it needs to decode the stream since it can’t probe the file itself..output(writeStream)+.run(): Properly initializes the ffmpeg process, which reads from the input stream, processes the video/audio, and writes the converted data to your output stream. The.pipe()method doesn’t handle the process initiation correctly when using a stream input, leading to no data being processed.
Bonus Tips
- Always include error handling to catch issues like missing ffmpeg binaries, invalid input streams, or format mismatches.
- If you’re unsure of the input format, you can use tools like
ffprobe(included with ffmpeg) to check before settinginputFormat.
内容的提问来源于stack exchange,提问作者Wise Colt

