👉 项目官网:https://www.python-office.com/ 👈

github star

大家好,这里是程序员晚枫,正在all in AI编程实战

今天教你怎么用 python-office 处理视频——压缩、剪辑、提取音频!

1、安装视频处理库

1
pip install moviepy

2、视频压缩

1
2
3
4
5
6
7
8
9
10
import office

# 压缩视频
office.video.compress(
path='原始视频.mp4',
output_file='压缩后.mp4',
bitrate='1000k' # 比特率,越小文件越小
)

print('视频压缩完成!')

3、视频剪辑(截取片段)

1
2
3
4
5
6
7
8
9
10
11
import office

# 截取视频片段(第30秒到第60秒)
office.video.cut(
path='长视频.mp4',
output_file='精彩片段.mp4',
start=30, # 开始时间(秒)
end=60 # 结束时间(秒)
)

print('视频剪辑完成!')

4、合并多个视频

1
2
3
4
5
6
7
8
9
import office

# 合并多个视频
office.video.concat(
file_list=['视频1.mp4', '视频2.mp4', '视频3.mp4'],
output_file='合并后.mp4'
)

print('视频合并完成!')

5、提取音频

1
2
3
4
5
6
7
8
9
import office

# 从视频提取音频
office.video.audio(
path='视频.mp4',
output_file='音频.mp3'
)

print('音频提取完成!')

6、生成缩略图

1
2
3
4
5
6
7
8
9
10
import office

# 生成视频缩略图
office.video.thumbnail(
path='视频.mp4',
output_file='封面.jpg',
time=5 # 第5秒的截图
)

print('缩略图生成完成!')

7、实战案例:批量压缩视频

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import office
import os

def batch_compress(folder):
"""批量压缩视频"""
os.makedirs('压缩后', exist_ok=True)

count = 0
for file in os.listdir(folder):
if file.endswith(('.mp4', '.avi', '.mov')):
src = os.path.join(folder, file)
dst = os.path.join('压缩后', file)

office.video.compress(path=src, output_file=dst, bitrate='800k')
count += 1
print(f'已压缩: {file}')

print(f'共压缩 {count} 个视频!')

batch_compress('视频文件夹')

8、实战案例:自动剪辑课程视频

把一个长的课程视频,按章节自动剪辑成多个短视频:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import office

# 课程章节信息
chapters = [
{'name': '第1章-Python基础', 'start': 0, 'end': 600},
{'name': '第2章-变量和数据类型', 'start': 600, 'end': 1200},
{'name': '第3章-条件判断', 'start': 1200, 'end': 1800},
{'name': '第4章-循环', 'start': 1800, 'end': 2400},
{'name': '第5章-函数', 'start': 2400, 'end': 3000}
]

# 剪辑视频
for chapter in chapters:
output = f"{chapter['name']}.mp4"
office.video.cut(
path='完整课程.mp4',
output_file=output,
start=chapter['start'],
end=chapter['end']
)
print(f'已剪辑: {output}')

print('课程视频剪辑完成!')

9、常见问题

Q:视频处理很慢?

A:视频处理本身需要时间,建议用 bitrate 参数降低质量以加快速度。

Q:Mac上能用吗?

A:可以,但需要安装 ffmpeg:brew install ffmpeg

Q:报错"找不到ffmpeg"?

A:需要安装 ffmpeg:

10、下讲预告

学会了视频处理,下一讲我们学 代码管理:自动备份和整理代码文件。

敬请期待!


有问题欢迎加微信 python-office 进群交流~

程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!