且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 ffmpeg 根据开始和结束时间剪切视频

更新时间:2023-09-22 13:04:46

您可能在 3 秒标记处没有关键帧.由于非关键帧对与其他帧的差异进行编码,因此它们需要从前一个关键帧开始的所有数据.

You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.

使用 mp4 容器,可以在非关键帧处进行剪切,而无需使用编辑列表重新编码.换句话说,如果 3s 之前最近的关键帧是 0s,那么它会复制从 0s 开始的视频,并使用编辑列表告诉播放器在 3 秒后开始播放.

With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.

如果您使用的是来自 git master 的 最新的 ffmpeg,当使用您的命令调用时,它将使用编辑列表执行此操作假如.如果这对您不起作用,那么您可能使用的是旧版本的 ffmpeg,或者您的播放器不支持编辑列表.有些播放器会忽略编辑列表,始终从头到尾播放文件中的所有媒体.

If you are using the latest ffmpeg from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.

如果您想从非关键帧开始精确剪切并希望它在不支持编辑列表的播放器上从所需点开始播放,或者想要确保剪切部分实际上不在输出文件中(例如,如果它包含机密信息),那么您可以通过重新编码来做到这一点,以便在所需的开始时间精确地有一个关键帧.如果您未指定 copy,则重新编码是默认设置.例如:

If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify copy. For example:

ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4

重新编码时,您可能还希望包含其他与质量相关的选项或特定的 AAC 编码器.有关详细信息,请参阅 ffmpeg 的 x264 编码指南视频和 音频的 AAC 编码指南.

When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's x264 Encoding Guide for video and AAC Encoding Guide for audio.

此外,-t 选项指定持续时间,而不是结束时间.上面的命令将从 3s 开始编码 8s 的视频.要从 3 秒开始到 8 秒结束,请使用 -t 5.如果您使用的是当前版本的 ffmpeg,您还可以将上述命令中的 -t 替换为 -to 以在指定时间结束.

Also, the -t option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use -t 5. If you are using a current version of ffmpeg you can also replace -t with -to in the above command to end at the specified time.