首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在播放媒体文件时添加结束Python循环

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

Stack Overflow用户
提问于 2020-07-19 13:22:21
回答 1查看 95关注 0票数 2

Python新手,使用Raspberry Pi、GPIO和pygame。如果播放媒体文件时按下了按钮,我想结束循环。

现在我有了它,所以你按下按钮,mp3文件就会一直播放(这是一个30分钟的剪辑)。我希望如果再次按下按钮,媒体将重置并从头开始播放。

我尝试添加一个中断和一个if语句,但它忽略了它,因为mp3文件已经在播放了。我该怎么做呢?

下面是我的代码:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-20 04:35:02

试试这个:

代码语言:javascript
复制
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/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62976607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档