视频与音频合并

首先要安装ffmpeg

import ffmpeg

def check_files(file1, file2):
    try:
        probe_video = ffmpeg.probe(file1)
        video_stream = next((stream for stream in probe_video["streams"] if stream["codec_type"] == "video"), None)
        duration_video = float(video_stream["duration"])

        probe_audio = ffmpeg.probe(file2)
        audio_stream = next((stream for stream in probe_audio["streams"] if stream["codec_type"] == "audio"), None)
        duration_audio = float(audio_stream["duration"])
        
        return duration_video, duration_audio
    except Exception as e:
        print(f"无法获取时长信息: {e}")
        exit()

def main():
    input_video = "1.mp4"
    input_audio = "1.mp3"

    # 检查文件是否存在以及它们的时长
    duration_video1, duration_audio = check_files(input_video, input_audio)

    # 如果音频文件比视频文件长,则裁剪音频以匹配视频长度
    if duration_audio > duration_video1:
        trim_start = f"0"
        trim_duration = f"{duration_video1}"
        input_audio_trimmed = f"{input_audio[:-4]}_trimmed.mp3"
        ffmpeg.input(input_audio).trim(start=trim_start, duration=trim_duration).output(input_audio_trimmed).run()
        input_audio = input_audio_trimmed

    # 合并视频和音频流,并输出到 out.mp4
    (
        ffmpeg
        .concat(
            ffmpeg.input(input_video),
            ffmpeg.input(input_audio, format="mp3"),
            v=1, a=1,
        )
        .output("out.mp4")
        .overwrite_output()
        .run()
    )

if __name__ == "__main__":
    main()

你可能感兴趣的:(音视频,python)