main.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from moviepy.editor import VideoFileClip, concatenate_videoclips
  2. import os
  3. import json
  4. def concat_videos(video_paths, output_path):
  5. """
  6. 拼接多个视频文件为一个视频。
  7. :param video_paths: 视频文件路径列表,例如 ['1.mp4', '2.mp4']
  8. :param output_path: 输出视频文件路径,例如 'output.mp4'
  9. """
  10. if not video_paths:
  11. raise ValueError("视频路径列表不能为空")
  12. clips = []
  13. for path in video_paths:
  14. if not os.path.isfile(path):
  15. raise FileNotFoundError(f"视频文件不存在: {path}")
  16. clips.append(VideoFileClip(path))
  17. # 拼接所有视频片段
  18. final_clip = concatenate_videoclips(clips, method="compose") # 使用 compose 可处理不同尺寸
  19. # 写入输出文件
  20. final_clip.write_videofile(
  21. output_path,
  22. codec='libx264',
  23. audio_codec='aac',
  24. temp_audiofile='temp-audio.m4a',
  25. remove_temp=True
  26. )
  27. # 关闭所有 clip 以释放资源
  28. for clip in clips:
  29. clip.close()
  30. final_clip.close()
  31. # 示例用法
  32. if __name__ == "__main__":
  33. # 生成视频片段
  34. with open("./output/storyboards_with_segments.json", "r", encoding='utf-8') as f:
  35. final_storyboards = json.load(f)[0]["storyboards"]
  36. segments = []
  37. for storyboard in final_storyboards:
  38. storyboard_path = storyboard["storyboard"]
  39. for item in storyboard_path:
  40. clip_path = item["clip_path"]
  41. segments.append(clip_path)
  42. videos = segments[30:40]
  43. print(videos)
  44. concat_videos(segments, "output_combined_4.mp4")