pygame按下按钮时播放文件夹中的随机音频文件

时间:2018-08-25 13:03:57

标签: python python-3.x pygame raspberry-pi3

每当我按下与GPIO连接的按钮时,我希望树莓播放文件夹中的随机音频文件。我已经编写了该程序的一个稍有不同的版本,但是不幸的是,每次按下该按钮时,它总是播放相同的文件,所以我必须重新启动该程序才能获得另一种声音。

sndA = pygame.mixer.Sound(random.choice(attack))
SoundA = pygame.mixer.Channel(1)
while True: 
       try: 
        if (GPIO.input(4) == True):
          SoundA.play(sndA)

这是完整的程序:

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)

1 个答案:

答案 0 :(得分:1)

加载所有声音并将其添加到列表中。

attack_sounds = []
for sound_file in glob.glob("attack/*.wav"):
    attack_sounds.append(pygame.mixer.Sound(sound_file))

然后使用此列表作为参数调用random.choice,从列表中选择随机声音并播放。

if GPIO.input(4):
    random_sound = random.choice(attack_sounds)
    random_sound.play()