Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a sound that is playing in Python?

So I have code that looks like this:

    import winsound
    from msvcrt import getch

    sound_path = "Path to sound"

    while True:
        key= ord(getch())
        if key == 27:
            break
        if key == 113: #theq key
            winsound.PlaySound(sound_path, winsound.SND_FILENAME)

So right now if I press the 'q' key, it plays the corresponding sound like it should. However if I keep pressing the 'q' key before the current sound is done playing, it will play after the current sound is finished. How would I have it so upon pressing the 'q' button, it would stop the current noise and play the next one?

like image 917
Joshua Kim Avatar asked May 03 '17 11:05

Joshua Kim


2 Answers

Edit: Having looked further into it (Win7, Python3.6.1), Eswcvlads answer is the way to go. When using the winsound.SND_ASYNC flag, you can immediately play another sound and the currently playing sound stops.

winsound.PlaySound(r'D:\seven_11.wav', winsound.SND_ASYNC)

-> plays seven_11

winsound.PlaySound(r'D:\seven_12.wav', winsound.SND_ASYNC)

-> seven_11 stops and seven_12 starts playing

However, to stop all playback, my original approach is still valid:

winsound.PlaySound(None, winsound.SND_PURGE)

From the docs:

winsound.PlaySound(sound, flags) ... If the sound parameter is None, any currently playing waveform sound is stopped.

So including that before calling PlaySound for the next one should stop the playback before starting the next.

like image 106
Christian König Avatar answered Sep 25 '22 19:09

Christian König


if key == 113: #theq key
        winsound.Playsound(None, windsound.SND_FILENAME)
        winsound.PlaySound(sound_path, winsound.SND_FILENAME)

If the sound parameter is None, any currently playing waveform sound is stopped. So do that before every sound file played.

like image 31
nikhalster Avatar answered Sep 22 '22 19:09

nikhalster