Reputation: 11
I want my raspberry to play a random audio file from a folder, everytime I press a button I connected with a GPIO. I already wrote a slightly different version of this program, but unfortunately it always plays the same file, everytime I press the button, so I have to restart the program to get another sound.
sndA = pygame.mixer.Sound(random.choice(attack))
SoundA = pygame.mixer.Channel(1)
while True:
try:
if (GPIO.input(4) == True):
SoundA.play(sndA)
Here's the complete program:
import pygame.mixer
import RPi.GPIO as GPIO
from sys import exit
import random
import time
import glob
import pygame.event
attack = glob.glob("attack/*.wav") #folder with attack quotes
move = glob.glob("movement/*.wav") #folder with move/idle quotes
taunt = glob.glob("taunt/*.wav") #folder with taunt quotes
joke = glob.glob("joke/*.wav") #folder with the jokes
laugh = glob.glob("laugh/*.wav") #folder with the laughing tracks
pick = glob.glob("pick/*.wav") #folder with pick/ban quotes
misc = glob.glob("misc/*.wav")
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN)
GPIO.setup(17, GPIO.IN)
GPIO.setup(18, GPIO.IN)
GPIO.setup(21, GPIO.IN)
GPIO.setup(23, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(25, GPIO.IN)
pygame.mixer.init(48000, -16, 1, 1024)
sndA = pygame.mixer.Sound(random.choice(attack))
sndB = pygame.mixer.Sound(random.choice(move))
sndC = pygame.mixer.Sound(random.choice(taunt))
sndD = pygame.mixer.Sound(random.choice(joke))
sndE = pygame.mixer.Sound(random.choice(laugh))
sndF = pygame.mixer.Sound(random.choice(pick))
sndG = pygame.mixer.Sound(random.choice(misc))
SoundA = pygame.mixer.Channel(1)
SoundB = pygame.mixer.Channel(2)
SoundC = pygame.mixer.Channel(3)
SoundD = pygame.mixer.Channel(4)
SoundE = pygame.mixer.Channel(5)
SoundF = pygame.mixer.Channel(6)
SoundG = pygame.mixer.Channel(7)
print ("Soundboard aktiv.");
while True:
try:
if (GPIO.input(4) == True):
SoundA.play(sndA)
if (GPIO.input(17) == True):
SoundB.play(sndB)
if (GPIO.input(18) == True):
SoundC.play(sndC)
if (GPIO.input(21) == True):
SoundD.play(sndD)
if (GPIO.input(23) == True):
SoundE.play(sndE)
if (GPIO.input(24) == True):
SoundF.play(sndF)
if (GPIO.input(25) == True):
SoundG.play(sndG);
except KeyboardInterrupt:
exit()
time.sleep(2)
Upvotes: 1
Views: 1214
Reputation: 20448
Load all sounds and append them to a list.
attack_sounds = []
for sound_file in glob.glob("attack/*.wav"):
attack_sounds.append(pygame.mixer.Sound(sound_file))
Then call random.choice
with this list as the argument to pick a random sound out of the list and play it.
if GPIO.input(4):
random_sound = random.choice(attack_sounds)
random_sound.play()
Upvotes: 1