0

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):

1 Answer 1

0

You can use subprocess 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" 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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.