JarochoEngineer
JarochoEngineer

Reputation: 1787

Read *.wav files in buffers

I need to read data from a *.wav file in buffers of specific amount. Until now I am able to read a wav file of 10 seconds using the wave library:

fp = wave.open('M1F1-int16-AFsp.wav')
nchan = fp.getnchannels()
N = fp.getnframes()
fr= fp.getframerate()
dstr = fp.readframes(N*nchan)
data = numpy.fromstring(dstr, numpy.int16)
data = numpy.reshape(data, (-1,nchan))

After I can write the file using the function open as writing mode with wave. With the previous source code, I can read a wave file and write a copy of the wave file. However, now I want to read and write the wav files in buffers of 2048. Do you know a better way to read and write wav files which are longer in size and is required to process by parts?

Thank you for your orientation

Upvotes: 2

Views: 3466

Answers (1)

lextoumbourou
lextoumbourou

Reputation: 463

The Wave.readframes(n) method takes a param controlling the size of the frames returned. We can calculate the frames size by dividing your buffer size (2048 bytes) by the sample width + the number of channels. We can then iterate through the file grabbing a bunch of frames this size and writing them to our output file.

As follows:

import wave

BUFFER_SIZE = 2048

fp = wave.open('M1F1-int16-AFsp.wav')

output = wave.open('output.wav', 'wb')
output.setparams(fp.getparams())

frames_to_read = BUFFER_SIZE / (fp.getsampwidth() + fp.getnchannels())

while True:
    frames = fp.readframes(frames_to_read)
    if not frames:
        break

    output.writeframes(frames)

Upvotes: 3

Related Questions