1.安装ffmpeg
pip install ffmpeg-python
2.编辑ffmpeg_util.py
# -*- coding: utf-8 -*-
import os;
import subprocess
import ffmpeg;
from Utils.time_util import *
ffmpegPath="";
def set_ffmpeg_path(path):
global ffmpegPath;
ffmpegPath = path;
# 获取视频长度
def get_video_length(input_file):
global ffmpegPath;
result = subprocess.run([ffmpegPath+"ffprobe", "-v", "error", "-show_entries",
"format=duration", "-of",
"default=noprint_wrappers=1:nokey=1", input_file],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return float(result.stdout)
# 获取音频长度
def get_audio_length(input_file):
global ffmpegPath;
script = f'{ffmpegPath}ffprobe -i "{input_file}" -show_entries format=duration -v quiet -of csv="p=0"'
result = subprocess.run(script,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return float(result.stdout)
#合成字幕
def combine_video_subtitles(input_file, input_srt, output_file):
global ffmpegPath;
data= input_srt[2:];
script = f'{ffmpegPath}ffmpeg -i "{input_file}" -vf subtitles=\'{data}\' "{output_file}" '
subprocess.run(script, shell=True)
#合并视频,音频资源
def combine_video(input_file, input_audio, output_file):
global ffmpegPath;
video_length = get_video_length(input_file);
script = f'{ffmpegPath}ffmpeg -i "{input_file}" -i "{input_audio}" -filter_complex "[0:v]trim=0:{video_length}[v];[1:a]adelay=10[a];[v][a]concat=n=1:v=1:a=1" -c:v libx264 -c:a aac -movflags +faststart "{output_file}" -y'
subprocess.run(script, shell=True)
#合并多个视频
def concat_assets(input_files,output_file):
global ffmpegPath;
datas = "|".join(input_files);
script = f'{ffmpegPath}ffmpeg -i "concat:{datas}" -c copy "{output_file}"'
subprocess.run(script, shell=True)
#通过文本文件合并视频,音频资源
def concat_by_file(input_file,output_file):
global ffmpegPath;
script = f'{ffmpegPath}ffmpeg -f concat -safe 0 -i "{input_file}" -c copy "{output_file}" -y'
subprocess.run(script, shell=True)
# 裁剪素材视频,制定时间范围
def copy_video(input_file,output_file, start_time, end_time):
global ffmpegPath;
script = f'{ffmpegPath}ffmpeg -i "{input_file}" -ss {start_time} -to {end_time} -c:v libx264 -crf 30 "{output_file}"'
subprocess.run(script, shell=True)
#调整视频fps
def change_fps(input_file,output_file,fps=30):
global ffmpegPath;
script = f'{ffmpegPath}ffmpeg -i "{input_file}" -vf "fps={fps}" -c:v libx264 -crf 30 -c:a copy "{output_file}" -y '
subprocess.run(script, shell=True)
# 裁剪视频区域(从中间开始)
def crop_video(input_file, output_file, new_width = 1080,new_height = 1920):
global ffmpegPath;
# 获取视频的元信息
probe = ffmpeg.probe(input_file,cmd=ffmpegPath+"ffprobe")
video_info = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
width = int(video_info['width'])
height = int(video_info['height'])
# 计算裁剪参数
x = (width - new_width) // 2
y = (height - new_height) // 2
# 裁剪视频
(
ffmpeg
.input(input_file)
.output(output_file, vf='crop={}:{}:{}:{}'.format(new_width, new_height, x, y))
.run(cmd=ffmpegPath+"ffmpeg")
)
注:记得下载ffmpeg工具,通过set_ffmpeg_path方法指定工具所在路径。