问题描述
我的 python 代码中有一个 PCM 音频帧流。有没有办法以附加到现有 .wav 文件的方式编写帧。我尝试过的是我正在使用 2 个 wav 文件。我正在从 1 个 wav 文件读取数据并写入现有的 wav 文件
import numpy
import wave
import scipy.io.wavfile
with open('testing_data.wav','rb') as fd:
contents = fd.read()
contents1=bytearray(contents)
numpy_data = numpy.array(contents1,dtype=float)
scipy.io.wavfile.write("whatstheweatherlike.wav",8000,numpy_data)
数据被附加到现有的 wav 文件中,但是当我尝试在媒体播放器中播放时 wav 文件已损坏
解决方法
使用 wave 库,您可以使用以下内容:
import wave
audiofile1="youraudiofile1.wav"
audiofile2="youraudiofile2.wav"
concantenated_file="youraudiofile3.wav"
frames=[]
wave0=wave.open(audiofile2,'rb')
frames.append([wave0.getparams(),wave0.readframes(wave0.getnframes())])
wave.close()
wave1=wave.open(audiofile2,'rb')
frames.append([wave1.getparams(),wave1.readframes(wave1.getnframes())])
wave1.close()
result=wave.open(concantenated_file,'wb')
result.setparams(frames[0][0])
result.writeframes(frames[0][1])
result.writeframes(frames[1][1])
result.close()
并且连接的顺序正是这里的写作顺序:
result.writeframes(frames[0][1]) #audiofile1
result.writeframes(frames[1][1]) #audiofile2