1

i have a tkinter button setup for my program. it plays a sound file. however, if i press the button while the audio is playing, the sound file will be queued and play again once its over. i want the button to be unresponsive (so it doesnt queue the audio) while its playing. this is my code:

soundInstructions = 0
def setSoundInstructions(filename):
    global soundInstructions
    soundInstructions = os.path.join(filename)

def playInstructions():
    playsound(soundInstructions)

soundButton = tkinter.Button(frame, image = soundImage, command = lambda: playInstructions(), borderwidth = 0, height= 25, width = 25)
soundButton.pack(side = TOP)
Cqrbon
  • 11
  • 3
  • You should probably look into an alternative audio library then. playsound doesn't provide any features such as checking the duration or time remaining on a track or create and signals or flags for when the audio track has finished. – Alexander Jun 23 '23 at 05:30

1 Answers1

0

This is a problem with the playsound library. When you click on the button and run the function, playsound will freeze the whole code until the sound is finished. To fix this, simply add a False after the file path.

def playInstructions():
    playsound(soundInstructions, False)

You can visit this answer for more information.


The reason why it works is because the playsound() function of the playsound library has 2 arguments, one is the file path that you put in, and the other one which you can set it to block the code or not.

In playsound.py:

def _playsoundWin(sound, block = True):
    [...]

If you set the block argument to False, it won't block the code.


The full code:

soundInstructions = 0
def setSoundInstructions(filename):
    global soundInstructions
    soundInstructions = os.path.join(filename)

def playInstructions():
    playsound(soundInstructions, False)

soundButton = tkinter.Button(frame, image = soundImage, command = lambda: playInstructions(), borderwidth = 0, height= 25, width = 25)
soundButton.pack(side = TOP)

NOTE: I don't recommend you to use the playsound library to play sounds in Python. Instead of that, you should use some other better alternatives such as winsound (Windows) or pygame.mixer.

Hung
  • 155
  • 10