使用Python的FFmpeg和MoviePy合并音视频时的音频截断/循环问题
裁剪背景视频匹配音频时长后,合并视频末尾出现音频截断/循环问题(FFmpeg 4.2.7 + Ubuntu 20.04)
我正在编写代码实现音频文件与背景视频的时长同步,但当裁剪背景视频以匹配音频时长时,生成的合并视频末尾会出现约0.2秒的音频截断或最后语句循环的问题。不执行裁剪步骤时,代码运行完全正常。
我使用Ubuntu 20.04系统和FFmpeg 4.2.7版本,已经尝试过修改编码格式、裁剪音频前后0.2秒或添加静音段,均无法解决问题。看到不少人遇到类似情况,请问有没有人解决过这个问题?
我的代码如下:
def merge_videos_with_subs( background_path, audio_path, subs, output_directory, output_filename ): try: # Load background video and audio background_clip = VideoFileClip(background_path) background_clip = background_clip.without_audio() audio_clip = AudioFileClip(audio_path) # Adjust video duration to match audio duration audio_duration = audio_clip.duration # If the background video is longer, trim it to match the audio duration if background_clip.duration > audio_duration: background_clip = background_clip.subclip(0, audio_duration) # If the audio is longer, loop the background video else: background_clip = background_clip.loop(duration=audio_duration) # Set audio of the background clip background_clip = background_clip.set_audio(audio_clip) # Overlay subtitles on the video final_clip = CompositeVideoClip( [background_clip, subtitles.set_pos(("center", "bottom"))] ) # Ensure the output directory exists os.makedirs(output_directory, exist_ok=True) # Define the output path output_path = os.path.join(output_directory, output_filename) # Write the merged video with subtitles final_clip.write_videofile( output_path, codec="libx264", audio_codec="aac", threads=4, fps=24 ) # Close the clips final_clip.close() background_clip.close() audio_clip.close() print(f"Merged video with subtitles saved to: {output_path}") except Exception as e: print(f"Error merging videos: {e}")
内容的提问来源于stack exchange,提问作者Stevenb123
相关产品推荐
相关产品推荐

