【发布时间】:2018-01-01 17:36:49
【问题描述】:
我正在尝试使用物理按钮在 Raspberry Pi 3 上触发 Python 中的音频样本。这个想法是,当我按下按钮时,会播放声音。我一直在使用 Pygame 库的通道来实现(或至少模仿)复音。
我一直在尝试实现的代码如下:(source)
def PlaySound(sound):
nextAvailableChannel = mixer.find_channel(True)
if nextAvailableChannel != None and nextAvailableChannel.get_busy() == False:
nextAvailableChannel.play(sound)
我的完整脚本如下:
#Import functions
import pygame.mixer as mixer
import RPi.GPIO as GPIO
from time import sleep
#Initialize mixer
mixer.init(48000, -16, 16, 1024)
#Pin setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#Create sound objects
bass = mixer.Sound('/home/pi/Desktop/Sounds/bass.wav')
snare = mixer.Sound('/home/pi/Desktop/Sounds/snare.wav')
hat = mixer.Sound('/home/pi/Desktop/Sounds/hihat.wav')
#Defining the channel-picking function
def PlaySound(sound):
nextAvailableChannel = mixer.find_channel(True)
if nextAvailableChannel != None and nextAvailableChannel.get_busy() == False:
nextAvailableChannel.play(sound)
print(sound, "button pressed")
sleep(sound / 10)
#Sounds are GO!
while True:
if GPIO.input(12) == False:
PlaySound(snare)
if GPIO.input(16) == False:
PlaySound(bass)
if GPIO.input(1) == False:
PlaySound(hat)
奇怪的是,没有print(sound, "button pressed"),声音就不会相互播放;声音一次只会播放一个。 (额外问题:为什么会这样?)
长话短说:有人知道实现复音的更好方法吗?
【问题讨论】:
标签: python raspberry-pi pygame