我的 RPi 附有 IOPi 板 . 当按下连接到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)