1. Problem
I need to segment a long video into some short video clips according to the time stamps I specify.
2. Code
#!/usr/bin/env python
'''
===========
Split Video
-----
Usage: ./split.py [video file name] [time file name]
'''
import os
def splitVideo(videofile, timefile):
f = open(timefile, "r")
cnt = 0
while True:
line = f.readline().strip('\n')
if line:
start, end = line.split(" ")
os.system('ffmpeg -i ' + videofile + ' -ss ' + str(start) + ' -vcodec copy -acodec copy -to ' + str(end) + ' ' + str(cnt) +'.mp4')
cnt = cnt + 1
else:
break
f.close()
if __name__ == '__main__':
print __doc__
import sys
try:
video = sys.argv[1]
time = sys.argv[2]
splitVideo(video, time)
except:
print "Please set input file."
3. Time Stamps
time.txt like this:
0 12
19 23
29 50
1:20 1:30
...
4. Feelings
- Python is an excellent tool as an system script language.
- I tried to code in shell, which is also an excellent script tool. But I failed to be familiar with its grammar and got lost in shell. This is the shell code I write:
#!/bin/bash
declare -i cnt
cnt=0
startTime=(0,0,0,0,0,0,0)
endTime=(0,0,0,0,0,0,0)
cat time.txt | while read line
do
begin=`echo $line | cut -d ' ' -f 1`
end=`echo $line | cut -d ' ' -f 2`
startTime[$cnt]=$begin
endTime[$cnt]=$end
echo $line
echo $begin,$end,$cnt
#echo "ffmpeg -ss ${begin} -i test00.mp4 -vcodec copy -acodec copy -t ${end} ${cnt}.mp4"
ffmpeg -ss ${begin} -i test00.mp4 -vcodec copy -acodec copy -t ${end} ${cnt}.mp4
cnt=$cnt+1
done
Shell code looks a little wired. Since it is more like a tool than a language.
The problem is, there is so mush powerful tools in linux, which can be used directly and freely in shell. Those amazing tools really attract me.