简体   繁体   中英

Extract a segment from a .wav file

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM