用python进行视频剪辑源码

简介: 这篇文章提供了一个使用Python进行视频剪辑的源码示例,通过结合moviepy和pydub库来实现视频的区间切割和音频合并。

需求

利用moviepy和pydub将一段视频进行区间切割

源码

# -*- encoding: utf-8 -*-
import os
from moviepy.video.io.VideoFileClip import VideoFileClip
from pydub import AudioSegment


def clip_video(source_file, target_file, start_time, stop_time):
    """
    利用moviepy进行视频剪切
    :param source_file: 原视频的路径,mp4格式
    :param target_file: 生成的目标视频路径,mp4格式
    :param start_time: 剪切的起始时间点(第start_time秒)
    :param stop_time: 剪切的结束时间点(第stop_time秒)
    :return:
    """
    validate_file(source_file)
    source_video = VideoFileClip(source_file)
    video = source_video.subclip(int(start_time), int(stop_time))  # 执行剪切操作
    video.write_videofile(target_file)  # 输出文件


def clip_audio(source_file, target_file, start_time, stop_time):
    """
    利用pydub进行音频剪切。pydub支持源文件为 mp4格式,因此这里的输入可以与视频剪切源文件一致
    :param source_file: 原视频的路径,mp4格式
    :param target_file: 生成的目标视频路径,mp4格式
    :param start_time: 剪切的起始时间点(第start_time秒)
    :param stop_time: 剪切的结束时间点(第stop_time秒)
    :return:
    """
    validate_file(source_file)
    audio = AudioSegment.from_file(source_file, "mp4")
    audio = audio[start_time * 1000: stop_time * 1000]
    audio_format = target_file[target_file.rindex(".") + 1:]
    audio.export(target_file, format=audio_format)


def combine_video_audio(video_file, audio_file, target_file, delete_tmp=False):
    """
    利用 ffmpeg将视频和音频进行合成
    :param video_file:
    :param audio_file:
    :param target_file:
    :param delete_tmp: 是否删除剪切过程生成的原视频/音频文件
    :return:
    """
    validate_file(video_file)
    validate_file(audio_file)
    # 注:需要先指定音频再指定视频,否则可能出现无声音的情况
    command = "ffmpeg -y -i {0} -i {1} -vcodec copy -acodec copy {2}".format(audio_file, video_file, target_file)
    os.system(command)
    if delete_tmp:
        os.remove(video_file)
        os.remove(audio_file)


def clip_handle(source_file, target_file, start_time, stop_time, tmp_path=None, delete_tmp=False):
    """
    将一个视频文件按指定时间区间进行剪切
    :param source_file: 原视频文件
    :param target_file: 目标视频文件
    :param start_time: 剪切的起始时间点(第start_time秒)
    :param stop_time: 剪切的结束时间点(第stop_time秒)
    :param tmp_path: 剪切过程的文件存放位置
    :param delete_tmp: 是否删除剪切生成的文件
    :return:
    """
    # 设置临时文件名
    if tmp_path is None or not os.path.exists(tmp_path):
        # 如果没有指定临时文件路径,则默认与目标文件的位置相同
        tmp_path = target_file[: target_file.rindex("/") + 1]
    target_file_name = target_file[target_file.rindex("/") + 1: target_file.rindex(".")]
    tmp_video = tmp_path + "v_" + target_file_name + ".mp4"
    tmp_audio = tmp_path + "a_" + target_file_name + ".mp4"

    # 执行文件剪切及合成
    clip_video(source_file, tmp_video, start_time, stop_time)
    clip_audio(source_file, tmp_audio, start_time, stop_time)
    combine_video_audio(tmp_video, tmp_audio, target_file, delete_tmp)


def validate_file(source_file):
    if not os.path.exists(source_file):
        raise FileNotFoundError("没有找到该文件:" + source_file)


def test_example():
    """
    测试例子
    :return:
    """
    root_path = 'XXX/videos/'
    video_name = "test.mp4"
    source_file = root_path + video_name
    start_time = 5
    stop_time = 6

    # 设置目标文件名
    target_name = str(start_time) + "_" + str(stop_time)
    target_file = root_path + "c_" + target_name + ".mp4"
    # 处理主函数
    clip_handle(source_file, target_file, start_time, stop_time)


if __name__ == "__main__":
    test_example()

三、遇到的问题

  1. moviepy切割后的视频没有声音

解决方案:通过pydub切割后再合并

  1. 合并时,不支持mp3、 wav等格式

解决方案:统一保存为mp4

相关文章
|
8天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
4天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2463 14
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
|
4天前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1502 14
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
|
1月前
|
运维 Cloud Native Devops
一线实战:运维人少,我们从 0 到 1 实践 DevOps 和云原生
上海经证科技有限公司为有效推进软件项目管理和开发工作,选择了阿里云云效作为 DevOps 解决方案。通过云效,实现了从 0 开始,到现在近百个微服务、数百条流水线与应用交付的全面覆盖,有效支撑了敏捷开发流程。
19274 29
|
1月前
|
人工智能 自然语言处理 搜索推荐
阿里云Elasticsearch AI搜索实践
本文介绍了阿里云 Elasticsearch 在AI 搜索方面的技术实践与探索。
18822 20
|
1月前
|
Rust Apache 对象存储
Apache Paimon V0.9最新进展
Apache Paimon V0.9 版本即将发布,此版本带来了多项新特性并解决了关键挑战。Paimon自2022年从Flink社区诞生以来迅速成长,已成为Apache顶级项目,并广泛应用于阿里集团内外的多家企业。
17515 13
Apache Paimon V0.9最新进展
|
6天前
|
编解码 JSON 自然语言处理
通义千问重磅开源Qwen2.5,性能超越Llama
击败Meta,阿里Qwen2.5再登全球开源大模型王座
365 11
|
1月前
|
存储 人工智能 前端开发
AI 网关零代码解决 AI 幻觉问题
本文主要介绍了 AI Agent 的背景,概念,探讨了 AI Agent 网关插件的使用方法,效果以及实现原理。
18697 16
|
2天前
|
算法 Java
JAVA并发编程系列(8)CountDownLatch核心原理
面试中的编程题目“模拟拼团”,我们通过使用CountDownLatch来实现多线程条件下的拼团逻辑。此外,深入解析了CountDownLatch的核心原理及其内部实现机制,特别是`await()`方法的具体工作流程。通过详细分析源码与内部结构,帮助读者更好地理解并发编程的关键概念。
|
2天前
|
SQL 监控 druid
Druid连接池学习
Druid学习笔记,使用Druid进行密码加密。参考文档:https://github.com/alibaba/druid
195 82