#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author:Aiker Zhao
@file:cut_media_all.py
@time:下午11:35
"""
import os
import re
import subprocess
from decimal import Decimal
from multiprocessing import Pool
path = r"/volume1/movie/201903/t1/"
new_path = r'/volume1/movie/201903/t2/'
if not os.path.exists(new_path):
os.mkdir(new_path)
else:
print(new_path + 'is ok!')
# 获取视频的 duration 时长 长 宽
def get_video_length(file):
process = subprocess.Popen(['ffmpeg', '-i', file], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
print(stdout)
pattern_duration = re.compile("Duration:\s(\d+?):(\d+?):(\d+\.\d+?),")
pattern_size = re.compile(",\s(\d{3,4})x(\d{3,4}),")
matches = re.search(pattern_duration, stdout.decode('utf-8'))
size = re.search(pattern_size, stdout.decode('utf-8'))
if size:
size = size.groups()
print(size)
if matches:
matches = matches.groups()
print(matches)
hours = Decimal(matches[0])
minutes = Decimal(matches[1])
seconds = Decimal(matches[2]) # 处理为十进制,避免小数点报错
total = 0
total += 60 * 60 * hours
total += 60 * minutes
total += seconds
width = size[0]
height = size[1]
return {
'total': total,
'width': width,
'height': height
}
def cutVideo(startPoint, file, endPoint, newFile):
command = ['ffmpeg', '-ss', startPoint, '-i', file, '-acodec', 'copy', '-vcodec', 'copy', '-t',
endPoint, newFile]
subprocess.call(command)
def millisecToAssFormat(t): # 取时间
s = t % 60
m = t // 60
if t < 3600:
h = 00
else:
h = t // 3600
return '%02d:%02d:%02d' % (h, m, s)
def main(file):
# for file in os.listdir(path):
# print(file)
videoInfo = get_video_length(file) # 视频信息
print(videoInfo)
if videoInfo:
duration = videoInfo.get('total') # 时长 秒
startPoint = 71 # 剪辑有片头片尾的视频 cut掉前71s后120s
startPoint = millisecToAssFormat(startPoint)
endPoint = duration - 120 # 120秒
endPoint = millisecToAssFormat(endPoint)
new_File = os.path.join(new_path, file) # 创建生成的文件路径+文件名
print(new_File, endPoint)
cutVideo(startPoint, file, endPoint, new_File)
if __name__ == '__main__':
# main()
file = [file for file in os.listdir(path) if os.path.isfile(file) == True]
pool = Pool()
pool.map(main, file)
pool.close()
pool.join()