gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:06:17 26 4
gpt4 key购买 nike

每次按下与 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)

最佳答案

加载所有声音并将它们附加到列表中。

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

关于python - 使用 pygame 按下按钮时播放文件夹中的随机音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52017596/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com