Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Playing wav in memory using winsound - SND_MEMORY

I'm trying to play a wav file from memory rather than a file. This is what I've tried but it doesn't work.

>>> with open('my/file/dir/sound.wav','rb') as f:
>>>     data = f.read()
>>> data = base64.b64encode(data)
>>> data = data.decode('UTF-8')

So now data is a string object that represent bytes of an audio wav file.

>>> winsound.PlaySound(data,winsound.SND_MEMORY)
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
RuntimeError: Failed to play sound

Please help. Where am I going wrong?

Edit: Nevermind. It's a bug.

like image 320
I_do_python Avatar asked Feb 25 '26 12:02

I_do_python


2 Answers

As per my understanding, the problem lies in the following line:

>>> data = data.decode('UTF-8')

When you are encoding with base64.b64encode() you should decode with base64.b64decode().

So, the code might be:

with open('my/file/dir/sound.wav','rb') as f:
    data = base64.b64encode(f.read())

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

I believe it solves the issue.

like image 101
Abhishek Kashyap Avatar answered Feb 28 '26 01:02

Abhishek Kashyap


Firstly, why are you encoding data like that? this is what i've done:

import winsound
memoryfile=open("myfilepath","rb")
winsound.PlaySound(memoryfile.read(), winsound.SND_MEMORY)

I've found that if you read the file before you tell winsound to play it it'll still play but will crash afterwards so don't do:

    memoryfile=open("myfilepath","rb").read()

also try using \\ instead of / for directories

like image 27
bthe1 Avatar answered Feb 28 '26 01:02

bthe1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!