0

i am trying to program a soundboard in python using gpiozero and a single button. Every time you press the button it should play the next sound. It almost works, but unfortunately not satisfactory yet.

Can you help me?

import pygame
from time import sleep
from gpiozero import Button
from signal import pause


pygame.init()

button = Button(4)

snd1 = pygame.mixer.Sound("/home/pi/test.wav")
snd2 = pygame.mixer.Sound("/home/pi/test2.wav")
snd3 = pygame.mixer.Sound("/home/pi/test3.wav")
snd4 = pygame.mixer.Sound("/home/pi/test4.wav")

while True:
    button.when_pressed = snd1.play
    button.when_pressed = snd2.play
    button.when_pressed = snd3.play
    button.when_pressed = snd4.play

pause()
2
  • 4
    What is 'not satisfactory' about it? – CoderMike Jan 29 at 23:28
  • it does not cycle through the sound files correctly. Maybe it is because the button is not debounced correctly? – Storm Jan 30 at 9:36
2

button.when_pressed should really be assigned once for simplicity. I've created a function playFile() to cycle through the sound files to be played.

Try the following:

import pygame
from time import sleep
from gpiozero import Button
from signal import pause

def playFile():
    global sndPos
    print('playFile',sndPos)
    pygame.mixer.stop()
    snds[sndPos].play()
    sndPos += 1
    if sndPos>3:
        sndPos = 0

pygame.init()

sndPos = 0
snds = [pygame.mixer.Sound("/home/pi/test.wav"),
        pygame.mixer.Sound("/home/pi/test2.wav"),
        pygame.mixer.Sound("/home/pi/test3.wav"),
        pygame.mixer.Sound("/home/pi/test4.wav")]
button = Button(4)
button.when_pressed = playFile

pause()
1
  • Wow thanks! I'm really new into python. Will try it right now – Storm Jan 30 at 11:54

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