简体   繁体   English

如何将 append 音频帧转换为 wav 文件 python

[英]how to append audio frames to wav file python

I have a stream of PCM audio frames coming to my python code.Is there way to write frame in a way that appends to an existing.wav file.我的 python 代码中有一个 stream PCM 音频帧。有没有办法以附加到现有.wav 文件的方式写入帧。 What i have tried is i am taking 2 wav files.我尝试过的是我正在使用 2 个 wav 文件。 From 1 wav file i am reading the data and writing to a existing wav file从 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)

data is getting appended in the existing wav file but the wav file is getting corrupted when i am trying to play in a media player数据被附加到现有的 wav 文件中,但是当我尝试在媒体播放器中播放时 wav 文件被损坏

With wave library you can do that with something like:使用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()

And the order of concatenation is exactly the order of the writing here:而连接的顺序正是这里的书写顺序:

result.writeframes(frames[0][1]) #audiofile1
result.writeframes(frames[1][1]) #audiofile2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM