Extract a segment from a .wav file

1.5k Views Asked by At

I have the following code to load a .wav file and play it:

import base64
import winsound
with open('file.wav','rb') as f:
    data = base64.b64encode(f.read())


winsound.PlaySound(base64.b64decode(data), winsound.SND_MEMORY)

It plays the file no problem but now I would like to extract a 'chunk' let's say from 233 to 300 and play that portion only.

seg = data[233:300]
winsound.PlaySound(base64.b64decode(seg), winsound.SND_MEMORY)

I Get: TypeError: 'sound' must be str or None, not 'bytes'

1

There are 1 best solutions below

0
On

PlaySound() is expecting a fully-formed WAV file, not a segment of PCM audio data. From the docs for PlaySound(), the underlying function called by Python's winsound:

The SND_MEMORY flag indicates that the lpszSoundName parameter is a pointer to an in-memory image of the WAVE file.

(emphasis added)

Rather than playing around with the internals of WAV files (though that isn't too hard, if you're interested), I'd suggest a more flexible audio library like pygame's. There, you could use the music module and it's set_pos function or use the Sound class to access the raw audio data and cut it like you proposed in your question.