1

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'

magicsword
  • 1,179
  • 3
  • 16
  • 26
  • 1
    I have no idea how wave files are actually encoded, and if you can just slice the data and expect it to work, but assuming you can, I'd try slicing the data itself and not the encoded data. Does b64decode work as expected if you truncate the expected padding? – jedwards Jun 04 '18 at 22:55

1 Answers1

0

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.

Linuxios
  • 34,849
  • 13
  • 91
  • 116