Search code examples
pythonbuttongpio

How to add end a Python loop while a media file is playing


New to Python, using Raspberry Pi, GPIO and pygame. I want to end a loop if a button is pressed while playing a media file.

Right now I have it so you press the button and the mp3 file plays all the way through (it is a 30 minute clip). I would like it so if the button is pressed again, the media resets and plays back from the beginning.

I have tried adding a break and an if statement but it just ignores it because the mp3 file is already playing. How would I go about doing this?

Here is what my code looks like:

while True:

while GPIO.input(buttonPin) == GPIO.LOW:
    if GPIO.input(buttonPin) == GPIO.LOW:
        pygame.mixer.init()
        pygame.mixer.music.load(open("audio.mp3"))
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            time.sleep(1)
    else:
        break

Solution

  • Try this:

    musicplay = False       #This variable will be used as a "toggle". When the button is pressed, it will flick from false to true, or true to false
    
    def playbackmedia(): # Define function that is called when button pin is pressed
            
            global musicplay # musicplay is a global variable that is outside of the scope of function
            
            musicplay = not musicplay # Here we are toggling the music play 
            
            if musicplay: # if music play is true, play music
                    pygame.mixer.init()
                    pygame.mixer.music.load(open("audio.mp3"))
                    pygame.mixer.music.play()
            else:  # if music play is false, stop the music
                    pygame.mixer.stop()
    
    def loop():
            
            #GPIO here add_event_detect will detect when the buttonPin has a falling edge (Just as the button is pressed)
            #The bounce time is to give you enough time for the signal to be read clearly. If this wasn't used, when you press the button,
            #because of mechanical vibration, the connections fluctuate and it could be read by the Pi as pressing the button really quickly over and over 
            #again until you let go of the button. You have 300 milliseconds to let go of the button before the playback media function is called
            
            GPIO.add_event_detect(buttonPin, GPIO.FALLING, callback=playbackmedia, bouncetime=300) 
            
            while True:
                   pass
    

    I recommend that you visit the pygame website for more details about how to control the mixer.

    https://www.pygame.org/docs/ref/mixer.html

    I also recommend you visit this website for more information about GPIO.RPi module

    https://sourceforge.net/p/raspberry-gpio-python/wiki/Examples/