'How to play song in pygame music for a set period of time or until a button is pushed?

I'm using pygame music to play an mp3 for a specific amount of time. However, how do I use a button to stop/fadeout of the song before the time is up? I've tried sleep, and sleep on a short loop, but its not detecting the button push.



Solution 1:[1]

Just call pygame.mixer.music.stop when the button is pushed.

if button_pushed:
    pygame.mixer.music.stop()

If you mat to fade out the music call pygame.mixer.music.fadeout(). The argument is the time in milliseconds

if button_pushed:
    pygame.mixer.music.fadeout(5000) # 5 seconds

Solution 2:[2]

Try this

from time import sleep

then

GPIO.setmode(GPIO.BCM)

GPIO.setup(0, GPIO.IN, pull_up_down=GPIO.PUD_UP)


#code before 10 sec count
Pygame.mixer.music.play()
interrupt = false
millisecondPassed = 0
while true:
    input_state = GPIO.input(18)
    if input_state == False:
        interrupt = true
    sleep(0.01) #wait for 1 millisecond
    millisecondPassed += 1
                
    if millisecondPassed >= 10000 or interrupt == true:
        break
#code after interruption

Finally

pygame.mixer.music.fadeout(5000)

or

pygame.mixer.music.stop()

As for reference: 10 seconds = 10000 milliseconds

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2