说明:这是本地简易AI自动剪辑脚本,实现功能:自动截取高光片段、按字幕/音频分割、合并输出成片。
依赖: moviepy 做视频剪辑、 openai‑whisper 做语音转文字识别分割,ffmpeg为底层依赖。
⚠️注意:处理大视频会消耗CPU,本地没有GPU速度会偏慢;仅供学习,不要用于处理无版权视频。
1.安装依赖
bash
pip install moviepy openai‑whisper
需要安装ffmpeg,windows下载配置环境变量,mac:brew install ffmpeg
2.完整代码
python
import whisper
from moviepy.editor import VideoFileClip, concatenate_clips
import os
class AIVideoAutoEdit:
def init(self, video_path):
self.video_path = video_path
self.model = whisper.load_model("base") # 模型可选 tiny/base/small,越大识别越好
self.clip = VideoFileClip(video_path)
def audio_transcribe(self):
"""语音识别,返回带时间戳的片段"""
print("🔍正在解析视频音频...")
result = self.model.transcribe(self.video_path, word_timestamps=True)
segments = result"segments"
return segments
def filter_useful_segment(self, segments, min_duration=2.0):
"""简单筛选:过滤太短静音片段,提取有效片段时间"""
keep_time = \[\]
for seg in segments:
start = seg"start"
end = seg"end"
dur = end - start
保留时长大于阈值的片段
if dur >= min_duration:
keep_time.append((start, end))
return keep_time
def auto_cut_video(self, output_name="ai_edit_output.mp4"):
seg_list = self.audio_transcribe()
time_ranges = self.filter_useful_segment(seg_list)
cut_clips = \[\]
print(f"✂️识别到 {len(time_ranges)} 个有效片段,开始剪辑")
for s, e in time_ranges:
sub = self.clip.subclip(s, e)
cut_clips.append(sub)
if len(cut_clips) == 0:
print("未识别有效片段")
return
final = concatenate_clips(cut_clips)
final.write_videofile(output_name, codec="libx264")
self.clip.close()
print(f"✅剪辑完成,输出文件:{output_name}")
if name == "main":
修改这里为你的本地视频路径
INPUT_VIDEO = "test.mp4"
if os.path.exists(INPUT_VIDEO):
edit = AIVideoAutoEdit(INPUT_VIDEO)
edit.auto_cut_video()
else:
print("视频文件不存在,请检查路径!")
程序实现逻辑
-
whisper提取视频音频,生成带时间戳字幕分段
-
过滤掉过短、静音无效片段
-
根据时间戳自动裁切视频片段
-
将有效片段拼接输出新视频
可以扩展升级方向
-
高光自动提取:接入音频响度检测,自动保留声音大的高光片段
-
关键词剪辑:识别字幕关键词,只保留出现指定关键词的片段
python
关键词筛选示例伪代码
keywords = "重点","注意","干货"
if any(k in seg"text" for k in keywords):
加入片段
-
自动加字幕、自动转横竖屏、加背景音乐
-
进阶:调用大模型API,把字幕文本发给LLM,让AI判断哪些片段值得保留
局限说明
-
whisper base模型 识别中文有小概率出错,换成 small 模型识别精度更高,但速度变慢
-
纯CPU运行长视频耗时很久,有N卡可以开启GPU加速
-
这只是基础demo,商业级AI剪辑一般调用第三方API(剪映开放平台、字节火山AI剪辑API),不建议从零手搓完整产品。