4

I'm using python 3.5 and I'm trying to play a sound while continuing right away with my script; according to https://docs.python.org/3.5/library/winsound.html the flag "winsound.SND_ASYNC" should be the way to go. However the following doesn't produce any sound:

import winsound
winsound.PlaySound('C:/Users/Bob/Sounds/sound.wav', winsound.SND_ASYNC)

Interesting enough if I change the flag to "winsound.SND_FILENAME the sound is played:

import winsound
winsound.PlaySound('C:/Users/Bob/Sounds/sound.wav', winsound.SND_FILENAME)

Any ideas why the async flag doesn't work?

Alex Stamate
  • 41
  • 1
  • 3
  • try to replace `C:/Users/Bob/Sounds/sound.wav` by `C:\Users\Bob\Sounds\sound.wav` – PRMoureu Jul 16 '17 at 12:07
  • 1
    It seems that you have to use two flags like, `winsound.PlaySound('C:/Users/Bob/Sounds/sound.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)` [_The sound parameter may be a filename, audio data as a string, or None. Its interpretation depends on the value of flags, **which can be a bitwise ORed combination** of the constants described below_](https://docs.python.org/3.5/library/winsound.html#winsound.PlaySound) – Himal Jul 16 '17 at 13:05
  • @Himal absolutely correct, and big thank you; it was driving me nuts :) – Alex Stamate Jul 16 '17 at 13:49
  • Glad it worked. I've posted it as an answer. – Himal Jul 16 '17 at 14:13

2 Answers2

4

According to the docs,

The sound parameter may be a filename, audio data as a string, or None. Its interpretation depends on the value of flags, which can be a bitwise ORed combination of the constants described below

Something like follows:

import winsound
winsound.PlaySound('C:/Users/Bob/Sounds/sound.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
Himal
  • 1,351
  • 3
  • 13
  • 28
0

Just in case somebody will google this with reason, that particularly winsound.SND_ASYNC flag is not working in combination with winsound.SND_FILENAME | winsound.SND_ASYNC, and everything working without it, just for winsound.SND_FILENAME - sometimes the problem is, when calling winsound at the end of your script, it will not be play with async flag, cause script already stopped, so it stops anything else with async flag. Check this out:

import winsound
import time


def wavsound(asynced=True):
    flags = winsound.SND_FILENAME | winsound.SND_ASYNC if asynced else winsound.SND_FILENAME
    winsound.PlaySound(r"path_to_your_wav_file", flags)


# it would or would not play at the end of your python script if:
wavsound(asynced=True)  # play if this line uncommented and wavsound(asynced=False) commented
# wavsound(asynced=False) # not play if this line uncommented and wavsound(asynced=True) commented

# time.sleep(2) # if uncomment this - play first 2 seconds and then cutoff with asynced=True
Hellohowdododo
  • 396
  • 3
  • 12