python [Python + FFMPEG]在不影响音高和/或连接多个剪辑的情况下改变视频速度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python [Python + FFMPEG]在不影响音高和/或连接多个剪辑的情况下改变视频速度相关的知识,希望对你有一定的参考价值。

import subprocess
from typing import List



ffmpeg_exe = "C:/__YOUR__/__PATH__/__TO__/ffmpeg.exe"

COMMAND_BASE =  [ffmpeg_exe]
COMMAND_BASE += ["-n"      ] # disable file overwriting



class Video():
  def __init__(self, path:str, speed:float=1.0):
    self.path  = path
    self.speed = speed



def concatenate_videos(videos:List[Video], output_file:str):
  video_count  = len(videos)
  video_speeds = [float(1/x.speed) for x in videos]
  audio_speeds = [float(x.speed  ) for x in videos]

  cmd_input_files = []
  filters, concat = ("", "")
  for i, x in enumerate(videos):
    cmd_input_files += ["-i", x.path]
    filters += f"[{i}:v] setpts = {video_speeds[i]} * PTS [v{i}];"
    filters += f"[{i}:a] atempo = {audio_speeds[i]}       [a{i}];"
    concat  += f"[v{i}][a{i}]"
  concat += f"concat = n = {video_count}:v = 1:a = 1 [v_all][a_all]"

  filter_complex = f"{filters}{concat}".replace(" ", "")

  cmd_filter_complex = [
    "-filter_complex", filter_complex,
  ]
  cmd_map = [
    "-map", "[v_all]",
    "-map", "[a_all]",
  ]
  command = sum([
    COMMAND_BASE,
    cmd_input_files,
    cmd_filter_complex,
    cmd_map,
    [output_file],
  ], [])

  subprocess.run(command)
from vid_utils import Video, concatenate_videos

videos = [
  Video(speed=1.0, path="C:/temp/my_video_1.mp4"),
  Video(speed=2.0, path="C:/temp/my_video_2.mp4"),
  Video(speed=0.5, path="C:/temp/my_video_3.mp4"),
]

concatenate_videos(videos=videos, output_file=f"C:/temp/output_video.mp4")

以上是关于python [Python + FFMPEG]在不影响音高和/或连接多个剪辑的情况下改变视频速度的主要内容,如果未能解决你的问题,请参考以下文章

python如何调用ffmpeg

python 使用ffmpeg在python中导出mp3

ffmpeg+Python实现B站MP4格式音频与视频的合并

ffmpeg 在 php 或 python 中获取元数据

python怎么执行ffmpeg

在python中使用ffmpeg获取视频时长