我正在建立一组带有运动传感器和覆盆子pi的音乐楼梯,这对python来说还很新。当前,当用户通过运动传感器时,便会在.wav文件的整个持续时间内播放音符,但我想知道是否有一种方法只能在运动传感器通过的时间内播放声音?
import RPi.GPIO as GPIO
import pygame.mixer
pygame.mixer.init()
'''GPIO setup'''
GPIO.setmode(GPIO.BCM)
GPIO.setwarningS(False)
'''Define stairs and GPIO pins'''
step1 = 4
step2 = 17
step3 = 27
'''Motion sensor setup'''
GPIO.setup(step1, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(step2, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(step3, GPIO.IN, GPIO.PUD_UP)
'''Sound files'''
C1 = pygame.mixer.Sound("piano/C1.wav")
D = pygame.mixer.Sound("piano/D.wav")
E = pygame.mixer.Sound("piano/E.wav")
def play(pin):
sound = sound_pins[pin]
sound.play()
'''Dictionary of steps and sounds'''
sound_pins = {
step1: C1,
step2: D,
step3: E,
}
for pin in sound_pins:
GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP)
GPIO.add_even_detect(pin, GPIO.RISING, play, 100)
答案 0 :(得分:0)
为GPIO.BOTH
添加一个事件监听器。触发此操作后,请使用input
检查这是上升沿还是下降沿,然后相应地调用play()
或stop()
。
像这样的事情,你会明白的:
def play(pin):
sound = sound_pins[pin]
if GPIO.input(pin):
sound.play()
else:
sound.stop()
for pin in sound_pins:
GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP)
GPIO.add_even_detect(pin, GPIO.BOTH, play, 100)