Skip to content
Advertisement

I need a way to stop a function from running at the push of a button

I’ve been working on this for hours, and I’ve tried everything from break in an if statement to making an index variable. I can’t seem to find a way to stop the sound/music from playing. My goal is to press ‘Q’ and stop the function and while loop to start another while loop.

import keyboard
import time
from playsound import playsound

#this handles the name that is displayed and makes it easier to input
def Song(type,opt):
        time = 1
        print(opt)
        playsound(type)

print('''Enter Your Music Selection:
O) Overworld
F) Fighting
B) Boss-Strong Enemy
V) Victory
I) Inside-Taven-Shop
D) Dungion
L) Lose-Death
    ''')

while True:
    while keyboard.is_pressed('O'):
        Song('MusicStuff/test0.wav','Overworld Theme')

    while keyboard.is_pressed('F'):
        Song('MusicStuff/TrashLine.wav','Fighting Theme')

Advertisement

Answer

Playsound consists of a single function which only plays sound, and does nothing else. That is why you are not able to “stop” the function.

If you want more interactivity you have to use a different library. You can use pyaudio.

Check out this post.

stopping audio with playsound module

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement