You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将16:9视频转为9:16并保留音频?

Python实现16:9转9:16视频(保留音频+无变形填充画布)

方案一:使用MoviePy(纯Python库)

核心逻辑:保持原视频宽高比,将视频缩放至适配9:16画布的最大尺寸,居中放置后用纯色填充空白区域,最后直接复用原音频导出。

from moviepy.editor import VideoFileClip, ColorClip, CompositeVideoClip

# 加载原视频
original_video = VideoFileClip("input_video.mp4")

# 设定9:16比例的目标画布分辨率(示例为1080x1920,可按需调整)
target_width = 1080
target_height = 1920

# 计算适配缩放比例
original_aspect = original_video.w / original_video.h
target_aspect = target_width / target_height

if original_aspect > target_aspect:
    # 原视频偏宽,按目标宽度缩放,高度自适应
    scaled_width = target_width
    scaled_height = int(scaled_width / original_aspect)
else:
    # 原视频偏高,按目标高度缩放,宽度自适应
    scaled_height = target_height
    scaled_width = int(scaled_height * original_aspect)

# 缩放原视频
scaled_video = original_video.resize(width=scaled_width, height=scaled_height)

# 创建目标尺寸的纯色画布(默认黑色,可修改color参数为RGB元组,如(255,255,255)为白色)
canvas = ColorClip(size=(target_width, target_height), color=(0,0,0), duration=original_video.duration)

# 将缩放后的视频居中放置在画布上
final_video = CompositeVideoClip([canvas, scaled_video.set_position("center")])

# 附加原音频
final_video = final_video.set_audio(original_video.audio)

# 导出视频,指定编码保证音画正常
final_video.write_videofile(
    "output_video.mp4",
    codec="libx264",
    audio_codec="aac",
    fps=original_video.fps
)

方案二:Python调用FFmpeg(高效稳定)

针对大视频场景,FFmpeg处理速度更快,通过subprocess直接调用命令行,精准控制画面调整逻辑,同时完整保留音频。

import subprocess

input_path = "input_video.mp4"
output_path = "output_video.mp4"

# FFmpeg命令:按比例缩放+居中填充黑边至9:16
ffmpeg_cmd = [
    "ffmpeg",
    "-i", input_path,
    "-vf", "scale=1080:-2,pad=1080:1920:(ow-iw)/2:(oh-ih)/2",
    "-c:v", "libx264",
    "-c:a", "copy",  # 直接复制原音频,无音质损失且速度快
    "-y",  # 覆盖已有输出文件
    output_path
]

# 执行命令
subprocess.run(ffmpeg_cmd, check=True)
  • 若需自定义填充颜色,可在pad滤镜后追加:color=white(或十六进制颜色值如#FFFFFF)。
  • 若原音频编码不兼容输出格式,可将-c:a copy改为-c:a aac重新编码。

内容的提问来源于stack exchange,提问作者Billi Alt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:27:28