ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

python 实现wav 左右通道内容一致

2026/8/24 23:44:29 拓冰建站 浏览量
python 实现wav 左右通道内容一致

实际项目中,需要左右通道一致的音源,通过audition 验证,仍发现 有bit 位会细微不一致,

验证方法如下:

wave_file ="LcopytoR光年之.wav"
#wave_file = "the_waiting_game_24bit_2ch.wav"
import wave
import numpy as np
import matplotlib.pyplot as plt# 打开音频文件
with wave.open(wave_file, 'rb') as wav_file:# 读取音频数据data = wav_file.readframes(wav_file.getnframes())print(f'wid{wav_file.getsampwidth()}')# 将数据转换为 NumPy 数组
audio_data = np.frombuffer(data, dtype=np.int16)
#audio_data = data# 获取左声道和右声道的数据
left_channel = audio_data[::2]  # 从第一个元素开始,每隔一个元素取一个,得到左声道数据
right_channel = audio_data[1::2]  # 从第二个元素开始,每隔一个元素取一个,得到右声道数据
final_out = 0
for i in range(len(left_channel)):abs_out = abs(left_channel[i]-right_channel[i])if final_out< abs_out:final_out = abs_out
print (f'diff:{final_out}\n')

所以,想通过脚本的形式复制一个左右通道一致的wav  脚本编写如下:

wave_file ="1ch.wav"
out_file  ="2ch.wav"
import wave
import numpy as np
# 打开原始音频文件
with wave.open(wave_file, 'rb') as wav_file:# 获取音频参数channels = wav_file.getnchannels()sample_width = wav_file.getsampwidth()sample_rate = wav_file.getframerate()frames = wav_file.getnframes()# 读取 24 位音频数据raw_data = wav_file.readframes(frames)# 将字节数据转换为 numpy 数组
audio_data = np.frombuffer(raw_data, dtype=np.int32)# 将数据复制到左右声道
left_channel = audio_data.copy()
right_channel = audio_data.copy()# 将数据合并为左右声道
stereo_data = np.column_stack((left_channel, right_channel))print(f'wid{sample_width},rate{sample_rate}ch{channels}')
# 创建一个新的音频文件,设置参数
with wave.open(out_file, 'wb') as out_wav_file:out_wav_file.setnchannels(2)  # 设置为双声道out_wav_file.setsampwidth(sample_width)out_wav_file.setframerate(sample_rate)# 将数据转换为字节格式byte_data = stereo_data.astype(np.int32).tobytes()out_wav_file.writeframes(byte_data)

后续通过上面的验证方法,发现左右结果无差别 ,留作备用记录下