如何用Python合并WAV文件并插入指定时长的静音间隔
实现方案
- 请确保两个待合并的WAV文件采样率、声道数、采样位深完全一致,否则合并后的音频会出现播放异常
- 若计算得到的
space_between为负数,说明两个音频总时长已经超过10秒,此时你可以根据需求裁剪音频或者调整总时长要求
以下是完整可运行的实现代码,不需要生成临时静音文件,直接在内存中插入对应时长的静音段即可:
import wave import struct # 读取两个待合并的WAV文件 file1 = wave.open('file_1.wav', 'rb') file2 = wave.open('file_2.wav', 'rb') # 校验音频参数是否匹配 assert file1.getparams() == file2.getparams(), "两个WAV文件参数不匹配,无法合并" params = file1.getparams() framerate = params.framerate sampwidth = params.sampwidth nchannels = params.nchannels # 计算两个音频总时长与所需静音时长 total_length = (file1.getnframes() + file2.getnframes()) / framerate space_between = 10 - total_length # 处理总时长超过10秒的异常场景 if space_between < 0: raise ValueError(f"两个音频总时长{total_length:.2f}秒已超过10秒,无法插入静音") # 读取两个音频的原始帧数据 frames1 = file1.readframes(file1.getnframes()) frames2 = file2.readframes(file2.getnframes()) # 生成指定时长的静音帧 silence_frames_count = int(framerate * space_between) if sampwidth == 2: # 16位深采样,静音对应采样值为0 silence_sample = struct.pack('<h', 0) elif sampwidth == 1: # 8位深采样,静音对应采样值为128 silence_sample = struct.pack('<B', 128) else: raise ValueError("当前仅支持8位或16位深的WAV文件") # 按声道数和静音时长拼接生成完整静音帧 silence_frames = silence_sample * nchannels * silence_frames_count # 按顺序拼接所有音频帧 all_frames = frames1 + silence_frames + frames2 # 写入合并后的输出文件 with wave.open('merged_output.wav', 'wb') as outfile: outfile.setparams(params) outfile.writeframes(all_frames) # 关闭文件句柄 file1.close() file2.close()
上述代码合并后的音频总时长刚好为10秒,如果需要支持更多位深的音频,补充对应位深的采样打包逻辑即可。
内容的提问来源于stack exchange,提问作者Michael Clauss
相关产品推荐
相关产品推荐

