import os
import wave
import numpy as np
import pyaudio
file1 = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), '音频文件/demo1.wav')
file2 = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), '音频文件/demo2.wav')
f1 = wave.open(file1, 'rb')
f2 = wave.open(file2, 'rb')
# 音频1的数据
params1 = f1.getparams()
nchannels1, sampwidth1, framerate1, nframes1, comptype1, compname1 = params1[:6]
print(nchannels1, sampwidth1, framerate1, nframes1, comptype1, compname1)
f1_str_data = f1.readframes(nframes1)
f1.close()
f1_wave_data = np.fromstring(f1_str_data, dtype=np.int16)
# 音频2的数据
params2 = f2.getparams()
nchannels2, sampwidth2, framerate2, nframes2, comptype2, compname2 = params2[:6]
print(nchannels2, sampwidth2, framerate2, nframes2, comptype2, compname2)
f2_str_data = f2.readframes(nframes2)
f2.close()
f2_wave_data = np.fromstring(f2_str_data, dtype=np.int16)
# 对不同长度的音频用数据零对齐补位
if nframes1 < nframes2:
length = abs(nframes2 - nframes1)
temp_array = np.zeros(length, dtype=np.int16)
rf1_wave_data = np.concatenate((f1_wave_data, temp_array))
rf2_wave_data = f2_wave_data
elif nframes1 > nframes2:
length = abs(nframes2 - nframes1)
temp_array = np.zeros(length, dtype=np.int16)
rf2_wave_data = np.concatenate((f2_wave_data, temp_array))
rf1_wave_data = f1_wave_data
else:
rf1_wave_data = f1_wave_data
rf2_wave_data = f2_wave_data
# ================================
# 合并1和2的数据
new_wave_data = rf1_wave_data + rf2_wave_data
new_wave = new_wave_data.tostring()
p = pyaudio.PyAudio()
CHANNELS = 1
FORMAT = pyaudio.paInt16
RATE = 44100
# 实现录音
def record(re_frames, WAVE_OUTPUT_FILENAME):
print("开始录音")
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(re_frames)
wf.close()
print("关闭录音")
record(new_wave, 'demo1+2.wav')