【发布时间】:2019-07-23 17:40:39
【问题描述】:
我对 python 很陌生,所以我没有太多经验。我正在创建一个 RPi 程序来使用切换开关 (https://ktechnics.com/wp-content/uploads/2015/12/mini-6a-125vac-spdt-mts-102-3-pin-2-position-on-on-toggle-switch.jpg) 播放和停止 7 首不同的歌曲。
我正在使用 GPIO 引脚的 PullUP/DOWN 电阻进行开关和 pygame.mixer.music 模块来播放歌曲。一首歌曲按预期工作:
import RPi.GPIO as GPIO
import pygame
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
pygame.init()
pygame.mixer.init()
cancion_1 = '/media/pi/PIERRE/0001.mp3'
while True:
switch_1 = GPIO.input(18)
if switch_1 == False:
if pygame.mixer.music.get_busy() == False:
print("Cancion 1 Sonando")
pygame.mixer.music.load(cancion_1)
pygame.mixer.music.play()
else:
if pygame.mixer.music.get_busy() == True:
print("Cancion 1 Callada")
pygame.mixer.music.stop()
但是当我尝试添加更多歌曲时,程序只播放第一首歌曲:
import RPi.GPIO as GPIO
import pygame
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_UP)
pygame.init()
pygame.mixer.init()
cancion_1 = '/media/pi/PIERRE/0001.mp3'
cancion_2 = '/media/pi/PIERRE/0002.mp3'
while True:
switch_1 = GPIO.input(18)
switch_2 = GPIO.input(19)
if switch_1 == False:
if pygame.mixer.music.get_busy() == False:
print("Cancion 1 Sonando")
pygame.mixer.music.load(cancion_1)
pygame.mixer.music.play()
elif switch_1 == True:
if pygame.mixer.music.get_busy() == True:
print("Cancion 1 Callada")
pygame.mixer.music.stop()
elif switch_2 == False:
if pygame.mixer.music.get_busy() == False:
print("Cancion 2 Sonando")
pygame.mixer.music.load(cancion_2)
pygame.mixer.music.play()
elif switch_2 == True:
if pygame.mixer.music.get_busy() == True:
print("Cancion 2 Callada")
pygame.mixer.music.stop()
我尝试为每首歌曲创建一个函数并稍后调用它,但它也不起作用。有什么想法吗??
【问题讨论】:
-
你需要重新思考你的逻辑。例如:如果
switch_1 == False:为真,则不会输入任何其他elif块。甚至if switch_2 == True:例如。另外,您想一次播放多首歌曲吗? -
没有。我不想一次播放超过一首歌曲。
标签: python python-3.x raspberry-pi pygame raspbian