pythonnumpywavnumpy-ndarraywaveform

Python - Convert Array of Float audio data to wav file


I have audio data recorded from microphone like this : (ndarray of float)

> print(data)
[-0.00762939 -0.00817871 -0.00714111 ...  0.0265511   0.02484207   0.02377392]

This is my code:

while(recording):
   frames.append(data)

waveFile = wave.open(WAVE_OUTPUT_FILENAME + "_" + str(COUNT_FILE) + ".wav", 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.wr(b''.join(frames))
waveFile.close()

But when I play the audio it become broken, nothing but just noise... how to convert it into .wav audio file?


Solution

  • you need to use pack your data first using struct

    replace your waveFile.writeframeswith this

    data=struct.pack( 'h' * len(frames), *frames )
    waveFile.writeframes(data)
    

    and maybe also convert your data to integers since I think wav files uses only integers values