剪切/拼接视频文件是一种常见需求。在线视频网站如今每每将一个视频文件分割成 n 段,以减小流量消耗。使用 DownloadHelper/DownThemAll 这类工具下载下来的每每就是分割后的文件。能实现剪切/拼接视频文件的工具多种多样,但每每都须要进行视频重编码(transcoding),这就不可避免的带来了视频质量上的损耗,更不用提那长的使人发指的转换时间了…git
其实借助 ffmpeg 咱们就能够在不进行视频重编码的状况下完成此类任务:github
剪切:bash
ffmpeg -i input.mp4 -ss **START_TIME** -t **STOP_TIME** -acodec copy -vcodec copy output.mp4
其中 START_TIME/STOP_TIME 的格式能够写成两种格式:ide
拼接 :工具
拼接的状况稍微复杂些,咱们须要将须要拼接的视频文件按如下格式保存在一个列表 list.txt 中:网站
file '/path/to/file1' file '/path/to/file2' file '/path/to/file3'
相应的命令为:编码
ffmpeg -f concat -i **list.txt** -c copy output.mp4
因为不须要重编码,这两条命令几乎是即时完成的。spa
方便起见,我写了一个脚原本简化操做。放在 github 上,请自取:
https://gist.github.com/imcaspar/8771268code
#!/bin/bash #cut/join videos using ffmpeg without quality loss if [ -z $1 ] || [ -z $2 ]; then echo "Usage:$0 c[ut] seconds <File>" echo " eg. $0 c 10 80 example.mp4" echo " eg. $0 c 00:00:10 00:01:20 example.mp4" echo "Usage:$0 j[oin] <FileType>" echo " eg. $0 j avi" exit fi case "$1" in c) echo "cuttig video..." fileName=$(echo $4 | cut -f 1 -d '.') fileType=$(echo $4 | cut -f 2 -d '.') ffmpeg -i $4 -ss $2 -t $3 -acodec copy -vcodec copy $fileName-$2-$3.$fileType ;; j) echo "joinning videos..." rm temp_list.txt for f in ./*.$2; do echo "file '$f'" >> temp_list.txt; done printf "file '%s'\n" ./*.$2 > temp_list.txt ffmpeg -f concat -i temp_list.txt -c copy output.$2 rm temp_list.txt ;; *) echo "wrong arguments" ;; esac exit
以上拼接操做生效的前提是,全部视频文件的格式编码相同,若是须要拼接不一样格式的视频文件能够借助如下脚本:
https://gist.github.com/imcaspar/8778002视频