按下按钮停止声音循环

2024-05-14 11:01:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个IOPi板连接到我的RPi。我试图让它播放一个声音时,一个按钮连接到I/O引脚被按下。你知道吗

这是通过一个类实现的,唯一的问题是,当按下按钮时,声音不断播放。 代码如下所示:

from ABElectronics_IOPi import IOPI
from time import sleep
import pygame
from inc import *
pygame.init()
global bus
InputPinNumber1 = 1
InputPinNumber2 = 1
bus1= IOPI(0x21)
bus2= IOPI(0x20)
while InputPinNumber1 <=34:
    bus1.setPinDirection(InputPinNumber1, 1)
    bus1.setPinPullup(InputPinNumber1, 1)
    bus1.invertPin(InputPinNumber1, 1)
    InputPinNumber1 +=1
    if InputPinNumber1 == 34:
    print("Bank 1 Ready ")
    break

while InputPinNumber2 <=34:
    bus2.setPinDirection(InputPinNumber2, 1)
    bus2.setPinPullup(InputPinNumber2, 1)
    bus2.invertPin(InputPinNumber2, 1)
    InputPinNumber2 +=1
    if InputPinNumber2 == 34:
    print("Bank 2 Ready ")
    break


class layout(object):
    def __init__(self, switch, bank, sound):
            self.switch=switch
            self.bank=bank
            self.sound=sound
            self.pre=0 
    def active(self):
                input1 = bus1.readPin(self.switch)
                input2 = bus2.readPin(self.switch)
            if(self.pre != input1) and (self.bank ==0):
                                    print("Button Press at pin " + str(self.switch))
                                    print("Switch " + str(self.switch))
                                    print("Bank " + str(self.bank))
                                    pygame.mixer.init()
                                    pygame.mixer.music.load(self.sound)
                                    pygame.mixer.music.play()
                                    sleep(3)
            if(self.pre != input2) and (self.bank ==1):
                                    print("Button Press at pin " + str(self.switch))
                                    print("Switch " + str(self.switch))
                                    print("Bank " + str(self.bank))
                                    pygame.mixer.init()
                                    pygame.mixer.music.load(self.sound)
                                    pygame.mixer.music.play()
                                    sleep(3)

Tags: importselfifinitpygamebankprintmixer

热门问题