使用MoviePy合成双音轨求助:添加音频时原音轨被替换
Got it, let's sort out this dual audio issue you're facing. The core problem here is that adding a new audio clip directly replaces the original track instead of mixing them. Here's a step-by-step approach to modify your code so you keep both the original audio and your new pond5.wav (with the new track quieter):
Step 1: Keep Your Original Video & Audio Intact
First, make sure your concatenated video retains its original audio tracks. The concatenate_videoclips function preserves audio by default, so we'll start with that:
from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip # Your existing setup media = "promo" # Replace `your_clip_list` with your actual list of video file paths clips = [VideoFileClip(clip) for clip in your_clip_list] final_video = concatenate_videoclips(clips)
Step 2: Prepare the New Audio (Adjust Volume)
Load your pond5.wav file and turn down its volume to sit below the original audio. Use volumex() to scale the volume—I'm using 0.3 (30% of original volume) here, but you can tweak this number to get the balance you want:
# Load new audio and reduce its volume new_audio = AudioFileClip("pond5.wav").volumex(0.3)
If your new audio is shorter than the final video and you want it to loop continuously, add .loop(duration=final_video.duration):
new_audio = AudioFileClip("pond5.wav").volumex(0.3).loop(duration=final_video.duration)
Step 3: Mix the Two Audio Tracks
Use CompositeAudioClip to combine the original video's audio with your adjusted new audio. This ensures both tracks play at the same time:
# Grab the original audio from your concatenated video original_audio = final_video.audio # Mix the two audio tracks, ensuring the new audio matches the video's duration mixed_audio = CompositeAudioClip([ original_audio, new_audio.set_duration(final_video.duration) ])
Step 4: Attach Mixed Audio to Video & Export
Finally, replace the video's audio with the mixed track and export your final video:
# Apply the mixed audio to the video final_video_with_dual_audio = final_video.set_audio(mixed_audio) # Export the finished video (adjust codecs if needed) final_video_with_dual_audio.write_videofile( f"{media}_dual_audio.mp4", codec="libx264", # Standard video codec audio_codec="aac" # High-quality audio codec )
Quick Notes:
- If any source clips lack audio,
original_audiomight returnNone—add a quick check for that if you run into errors. - The layer order in
CompositeAudioClipdoesn’t affect volume balance here, but you can add fade effects or timing adjustments if you want one track to take priority in specific sections. - Test different volume values (0.2 to 0.5 are good starting points) to find the perfect mix for your video.
内容的提问来源于stack exchange,提问作者Anay Bose

