Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. What I have tried is I am taking 2 wav files. From 1 wav file I am reading the data and writing to a existing wav file

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.

like image 453
Yashu Gupta Avatar asked May 03 '26 10:05

Yashu Gupta


1 Answers

With wave library you can do that with something like:

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
like image 138
Younes Avatar answered May 05 '26 22:05

Younes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!