I tried downloading the file and playing it using winsound to play it with the flag SND_MEMORY, but it only accepts str instead of the bytes object I got from urllib.request.urlopen. Using decode() needs a valid encoding, but I don't have one.
CLARIFICATION:downloading the file I mean as using urllib.request.urlopen to do it.

Dani AI

Generated

you do not need to decode anything. urllib.request.urlopen(...).read() already gives you raw bytes, and winsound.PlaySound can consume those bytes directly when you pass SND_MEMORY. In other words: keep the data as bytes and play it; do not convert to str. The only catch is that memory playback is synchronous, and you must not combine it with SND_ASYNC. (docs.python.org)

Play a remote WAV entirely from memory:

import urllib.request
import winsound

url = "https://example.com/sound.wav"

with urllib.request.urlopen(url) as r:
    data = r.read()  # bytes, not str

# Synchronous play from a WAV memory image
winsound.PlaySound(data, winsound.SND_MEMORY)

If you want non-blocking playback, write the download to a temporary file and then play it as a filename. This keeps your code snappy without leaving a permanent file around, and it is essentially what ’s approach accomplishes, just using a temp file instead of saving beside your script:

import urllib.request, tempfile, winsound, os

url = "https://example.com/sound.wav"

with urllib.request.urlopen(url) as r, tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
    f.write(r.read())
tmp_path = f.name

winsound.PlaySound(tmp_path, winsound.SND_FILENAME | winsound.SND_ASYNC)

# remove when you know playback has finished
# os.remove(tmp_path)

Notes:

  • urlopen(...).read() returns bytes by design; no decoding is needed for WAV. (docs.python.org)
  • SND_MEMORY expects a WAV memory image and cannot be combined with SND_ASYNC; use a filename for async playback. (docs.python.org)

Use urlretrieve,something like this.

import winsound    
try:
    # Python2
    from urllib import urlretrieve
except ImportError:
    # Python3
    from urllib.request import urlretrieve

def play(sound):
    winsound.PlaySound(sound, winsound.SND_FILENAME)

# Download wave file and save to disk
url = ""
filename = url.strip().split('/')[-1]
urlretrieve(url, filename)
print("Sound saved as {}".format(filename))

# Play wave file
play(filename)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.