为了账号安全,请及时绑定邮箱和手机立即绑定

如何在播放媒体文件时添加结束 Python 循环

如何在播放媒体文件时添加结束 Python 循环

茅侃侃 2023-03-16 17:57:09
Python 新手,使用 Raspberry Pi、GPIO 和 pygame。如果在播放媒体文件时按下按钮,我想结束循环。现在我有了它,所以你按下按钮,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 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信