我正在尝试创建一个在音频文件和后台文件之间根据持续时间进行同步的代码。 创建合并视频时,我听到最后一句话的剪切或循环声音大约 0.2 秒。 我尝试用多种不同的方法来解决这个问题,如下所列。
有人解决这个问题了吗?我看到很多人都有类似的问题。 我使用的是 Ubuntu 版本 20.04 和 ffmpeg 版本 4.2.7
这是我的代码:
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}")
我尝试过更改编解码器,尝试在合并前后剪切 0.2 秒的音频或将其静音,但似乎没有任何帮助。当我在没有背景子剪辑的情况下运行代码来匹配音频时,它工作得完美无缺。 如果我让后台运行到其完整持续时间或使其循环播放,则不会出现音频问题。看起来问题出在切割部分。
加载文件后,去掉最后的毛刺。这是 Moviepy 库中的一个错误。
audioclip = audioclip.subclip(0,-0.15)
我从这个问题中得到了答案。 [Python][Moviepy] 如何在音频末尾添加短暂的静音?