Last active
June 17, 2021 06:39
-
-
Save musan6363/39ed26b8ffe5e012fb9e02c96e99d833 to your computer and use it in GitHub Desktop.
ffmpegを使ってテキストファイルにリストアップした動画を任意の長さに分割する.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
####################################################################### | |
# ffmpegを使って動画を任意の長さで分割する. | |
# 71秒の動画ファイル video.mp4を30秒で切り取ると, | |
# 30sのvideo_1.mp4, 30sのvideo_2.mp4, 11sのvideo_3.mp4が生成される | |
# テキストファイルには対象となる動画のパスが必要.相対パスでもOK | |
# 実行したディレクトリに"cutvideo"ディレクトリが作られる | |
# 実行方法 | |
# sh splitvideo.sh <対象動画をリストアップしたtxt> <カットする長さ[s]> | |
# 実行例 | |
# sh ./splitvideo.sh ./target.sh 20 | |
####################################################################### | |
# カットする動画の長さ(引数で秒単位で指定可能.デフォルトは30秒) | |
cut_length=30 | |
if [ $# -eq 2 ]; then | |
cut_length=$2 | |
fi | |
# 失敗した動画のファイル名をまとめたテキストファイル | |
targettxt=$1 | |
# すでに書き出し先のファイルが有れば消す. | |
if [ -e cutvideo ]; then | |
rm -rf cutvideo | |
fi | |
mkdir cutvideo | |
use_ffmpeg () { | |
title=`basename $1 .mov` # パスと拡張子を除く | |
# ffmpegで動画の詳細を表示 | |
# Durationを含む行を抜粋 | |
# 2列目(Duration: 00:17:38.07, start: 0.000000, bitrate: 2588 kb/s)を表示 | |
# ","を削除 | |
raw_length=`ffmpeg -i $1 2>&1 | grep Duration | awk '{print $2}' | tr -d ,` | |
rest=$((${raw_length:0:2}*3600+${raw_length:3:2}*60+${raw_length:6:2})) | |
cutcnt=1 | |
while [ $rest -gt $cut_length ] | |
do | |
start=$(((cutcnt-1)*cut_length)) | |
echo "上$1, ${cutcnt}" | |
ffmpeg -ss ${start} -i $1 -t ${cut_length} -c copy "cutvideo/${title}_${cutcnt}.mp4" | |
cutcnt=$((cutcnt+1)) | |
rest=$((rest-cut_length)) | |
done | |
start=$(((cutcnt-1)*cut_length)) | |
echo "下$1, ${cutcnt}" | |
ffmpeg -ss ${start} -i $1 -c copy "cutvideo/${title}_${cutcnt}.mp4" | |
} | |
# 2重whileでループさせるとファイルのreadに失敗するので分割 | |
# readが保持していた次読む位置の情報が壊れる? | |
# 先にファイルリストを配列に保持して,その配列を順に参照する | |
i=0 | |
while read target | |
do | |
videos[$i]=$target | |
i=$((i+1)) | |
done < ${targettxt} | |
for ((i=0; i<${#videos[@]}; i++)) | |
do | |
use_ffmpeg ${videos[i]} | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment