How do I make button press first stopping a playing audio file and then playing its own audio?
Question: My problem is, that the audio files under each button are quite lengthy and if
I pressed the wrong button, I would have to wait it to play to end. How can I
make every button press to 1) stop the possible playing audio file and then 2)
play it's own file? I'm using mpg123 to play the audio files and file names
are placeholders.

Code:

    
    
    #!/usr/bin/env python
    
    import os
    from time import sleep
    import RPi.GPIO as GPIO
    
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.IN)
    GPIO.setup(19, GPIO.IN)
    GPIO.setup(20, GPIO.IN)
    GPIO.setup(21, GPIO.IN)
    GPIO.setup(22, GPIO.IN)
    GPIO.setup(23, GPIO.IN)
    GPIO.setup(24, GPIO.IN)
    GPIO.setup(25, GPIO.IN)
    GPIO.setup(26, GPIO.IN)
    GPIO.setup(27, GPIO.IN)
    
    while True:
    
        if (GPIO.input(18)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(19)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(20)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(21)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(22)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(23)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(24)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(25)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(26)==False):
            os.system('mpg123 audio.mp3 &')
        if (GPIO.input(27)==False):
            os.system('mpg123 audio.mp3 &')
    
    sleep(0.1):
    


Answer: You can use [subprocess](https://docs.python.org/3/library/subprocess.html)
asynchronously so the function call returns immediately. I think it is
possible to get a "handle" object to communicate with the external process
that also allows you to
"[kill](http://stackoverflow.com/questions/16866602/kill-a-running-subprocess-
call)" it.

Similarly, you could check your keys in the main program and start a thread
for playing: <http://docs.python.org/3/library/threading.html> (does not make
much sense as the other program is a new process anyway).

