1

sorry i'm new to this and it might sound dumb, but I have to achieve the following task:

You have three push buttons. Each button is connected to a pin. When the switch is pressed, an LED which is connected to another pin will light up and a song will be played for X amount of seconds:

#!/usr/bin/python

import os
import time
from time import sleep

import RPi.GPIO as GPIO
import pygame

GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.IN)
GPIO.setup(3, GPIO.IN)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)


while True:
        if (GPIO.input(2) == False):
                pygame.mixer.init(48000, -16, 1, 1024)
                pygame.mixer.music.load("/home/pi/Shaerwater.mp3")
                pygame.mixer.music.play()
                pygame.mixer.music.set_volume(1)
                while pygame.mixer.music.get_busy() == True:
                        GPIO.output(11, False)
                        if (GPIO.input(3) == False) :
                                pygame.mixer.music.stop()
                                GPIO.output(11, True)

        if (GPIO.input(3) == False):
                pygame.mixer.init(48000, -16, 1, 1024)
                pygame.mixer.music.load("/home/pi/Yelkouan.mp3")
                pygame.mixer.music.play()
                pygame.mixer.music.set_volume(1)
                while pygame.mixer.music.get_busy() == True:
                        GPIO.output(17, False)
                        if (GPIO.input(2) == False) :
                                pygame.mixer.music.stop()
                                GPIO.output(17, True)


#to reduce msgs
        sleep(0.2);
enter code here

Managed to get it to work, but please if you can recommend a cleaner script.

Thanks!

  • 1
    user1616681's answer here isn't exactly what you're looking for, but I think it's worth investigating. They used mplayer to achieve the same effect (play sound for X seconds, stop on interrupt). – goobering Jul 11 '16 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.