import moviepy.editor as mp


def concat_gif_list(gifs, output):
    clips = []
    for gif in gifs:
        clips.append(mp.VideoFileClip(gif))
    final = mp.concatenate_videoclips(clips)
    final.write_videofile(output)
    print(f"@合并生成GIF:{output}")


def merge_video_audio(video, audio, output):
    v = mp.VideoFileClip(video)
    video_duration = v.duration
    print("video_duration:", video_duration)

    a = mp.AudioFileClip(audio)
    audio_duration = a.duration
    video_start = 0
    audio_start = 0
    audio_clips = []
    while video_start < video_duration:
        video_rest = video_duration - video_start
        audio_rest = audio_duration - audio_start
        step = min(video_rest, audio_rest)
        slice = a.subclip(audio_start, step)
        audio_clips.append(slice)
        video_start += step
        audio_start += step
        if audio_start >= audio_start:
            audio_start = 0
    final_audio = mp.concatenate_audioclips(audio_clips)
    print("audio_duration:", final_audio.duration)

    final = v.set_audio(final_audio)
    final.write_videofile(output)

    print(f"@合成视频和音频:{output}")
