Menu

Split a video into equal parts with ffmpeg.wasm (and why to force keyframes)
📰

Split a video into equal parts with ffmpeg.wasm (and why to force keyframes)

DEV Community: webdev·media extractr·3 days ago
#a8ptbop7
#devtowebdev#devto#dev#ffmpeg#file
Long article (383 words) — no AI summary yet.
Reading 0:00
15s threshold

I build Mediaextractr , a set of file tools that run in the browser. One of them splits a video into equal parts, or into pieces of a set length. Here is how it works with ffmpeg.wasm, and the one flag that matters most.

The tempting shortcut

You can split with stream copy ( -c copy ). It is very fast, because nothing is re-encoded. The catch: a copied segment can only begin on a keyframe that already exists in the source. If you ask for 30 second pieces and the keyframes do not fall on those marks, the pieces come out longer or shorter than you asked.

Re-encode and force a keyframe at every cut

So the tool re-encodes, and tells the encoder to place a keyframe exactly where each cut will be:

ffmpeg -i input.mp4 \ -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1" \ -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p \ -c:a aac -b:a 160k \ -force_key_frames "expr:gte(t,n_forced*30)" \ -f segment -segment_time 30 -reset_timestamps 1 \ -map 0:v:0 -map "0:a:0?" \ part%03d.mp4

Enter fullscreen mode

Exit…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.