如果检测到物体,则播放声音

时间:2018-10-25 12:06:43

标签: python raspberry-pi pygame

我正在使用树莓派开发对象检测模型。我已经使用Google的对象检测API来检测模型,我的问题是当检测到特定类别的对象(例如人(即'id':22))时如何播放声音。

我已经尝试了一下,我来到的代码是这个,

if 22 in classes:
    threading.Thread(play_sound()).start()
def play_sound():
    pygame.init()
    pygame.mixer.music.load("")
    pygame.mixer.music.play(1,0.0)
    pygame.time.wait(5000)
    pygame.mixer.stop()

在这段代码中,我遇到的问题是

  1. 声音甚至在检测到对象之前就开始播放,我尝试调试,但不知道为什么。
  2. 我要重新启动同一线程
  3. 如果我使用其他线程,则pi会耗尽资源,并且整个执行会停止

有什么办法可以使它正常工作吗?

预先感谢

1 个答案:

答案 0 :(得分:1)

不要使用线程(不需要线程),不要使用pygame.time.wait,如果不想将其用于背景音乐,也不要使用pygame.mixer.music

使用Sound object(如果需要使用play函数,可以提供maxtime)。

因此您的代码应更像这样:

pygame.init()
detected_sound = pygame.mixer.Sound('filename')

...
    if 22 in classes:
        # use loops=-1 if the sound's length is less than 5 seconds
        # so it's repeated until we hit the maxtime of 5000ms
        detected_sound.play(loops=-1, maxtime=5000)
...
相关问题