Why these two WAV-creating functions are not producing identical output?

43 Views Asked by At

I am using these functions (that receive a pyaudio input) to produce an audio object usable on torchaudio. However, only "write2" produces a result that works, but not "write1".

def write2(recording):
    n_files = len(os.listdir(f_name_directory))
    filename = os.path.join(f_name_directory, 'file.wav')
    wf = wave.open(filename, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(recording)
    wf.close()
    with open('file.wav', 'rb') as f:
            buffer = io.BytesIO(f.read())
    return buffer


def write1(recording):
    buffer = io.BytesIO()
    wave_write = wave.open(buffer, 'wb')
    wave_write.setnchannels(CHANNELS)
    wave_write.setsampwidth(p.get_sample_size(FORMAT))
    wave_write.setframerate(RATE)
    wave_write.writeframes(recording)
    wave_write.close()
    return buffer

What do I need to do for write1 become equivalent to write2 without the i/o operations?

1

There are 1 best solutions below

0
On

As said by @jasonharper on the opening post comment, the solution was to insert buffer.seek(0) at the end of the function before returning it.

(...)
    wave_write.close()
    buffer.seek(0)
    return buffer