亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在播放媒體文件時添加結束 Python 循環

如何在播放媒體文件時添加結束 Python 循環

茅侃侃 2023-03-16 17:57:09
Python 新手,使用 Raspberry Pi、GPIO 和 pygame。如果在播放媒體文件時按下按鈕,我想結束循環?,F在我有了它,所以你按下按鈕,mp3 文件就會一直播放(這是一個 30 分鐘的剪輯)。我希望如此,如果再次按下按鈕,媒體會重置并從頭開始播放。我嘗試添加一個 break 和一個 if 語句,但它只是忽略它,因為 mp3 文件已經在播放。我該怎么做呢?這是我的代碼的樣子:while True:while GPIO.input(buttonPin) == GPIO.LOW:    if GPIO.input(buttonPin) == GPIO.LOW:        pygame.mixer.init()        pygame.mixer.music.load(open("audio.mp3"))        pygame.mixer.music.play()        while pygame.mixer.music.get_busy():            time.sleep(1)    else:        break
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

嘗試這個:


musicplay = False       #This variable will be used as a "toggle". When the button is pressed, it will flick from false to true, or true to false


def playbackmedia(): # Define function that is called when button pin is pressed

        

        global musicplay # musicplay is a global variable that is outside of the scope of function

        

        musicplay = not musicplay # Here we are toggling the music play 

        

        if musicplay: # if music play is true, play music

                pygame.mixer.init()

                pygame.mixer.music.load(open("audio.mp3"))

                pygame.mixer.music.play()

        else:  # if music play is false, stop the music

                pygame.mixer.stop()


def loop():

        

        #GPIO here add_event_detect will detect when the buttonPin has a falling edge (Just as the button is pressed)

        #The bounce time is to give you enough time for the signal to be read clearly. If this wasn't used, when you press the button,

        #because of mechanical vibration, the connections fluctuate and it could be read by the Pi as pressing the button really quickly over and over 

        #again until you let go of the button. You have 300 milliseconds to let go of the button before the playback media function is called

        

        GPIO.add_event_detect(buttonPin, GPIO.FALLING, callback=playbackmedia, bouncetime=300) 

        

        while True:

               pass

我建議您訪問 pygame 網站以獲取有關如何控制混音器的更多詳細信息。


https://www.pygame.org/docs/ref/mixer.html


我還建議您訪問此網站以獲取有關 GPIO.RPi 模塊的更多信息


https://sourceforge.net/p/raspberry-gpio-python/wiki/Examples/


查看完整回答
反對 回復 2023-03-16
  • 1 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號