Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果检测到物体,则播放声音_Python_Raspberry Pi_Pygame - Fatal编程技术网

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

Python 如果检测到物体,则播放声音,python,raspberry-pi,pygame,Python,Raspberry Pi,Pygame,我正在使用raspberry Pi开发一个对象检测模型。我已经使用谷歌的对象检测API来检测模型,我的问题是当检测到特定类别的对象(比如人类(即id:22))时,如何播放声音 我试过一点,我得到的代码是 if 22 in classes: threading.Thread(play_sound()).start() def play_sound(): pygame.init() pygame.mixer.music.load("") pygame.mixer.mu

我正在使用raspberry Pi开发一个对象检测模型。我已经使用谷歌的对象检测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()
在这段代码中,我遇到的问题是

  • 声音甚至在检测到对象之前就开始播放,我尝试过调试,但不知道为什么
  • 我又开始同一条线了
  • 如果使用不同的线程,pi将耗尽资源,整个执行将停止
  • 有什么办法可以让它工作吗

    提前感谢

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

    使用一个(如果您想使用它的功能,可以提供一个
    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)
    ...
    

    这个问题实际上与
    机器学习
    目标检测
    无关-请不要垃圾邮件标记(已删除)。作为一个正交问题,我建议您将
    pygame.init()
    pygame.mixes.music.load(…)
    移出
    play\u sound()
    。不要把构建和运行混为一谈。那么,你检查过你的“类”变量了吗?它可能总是包含22吗?@G.Brown不,它不总是包含“22”,当它检测到一个人时,它只包含“22”。我认为dedObed询问的是当前时差是多少,而不是期望/预期的时差。