Reputation: 509
I'm working on an object detection model using raspberry Pi. I've used Google's Object Detection API to detect models, My question is how to play sound when an object of a specific class(say human (i.e 'id' : 22))is detected.
I've tried a little and the code I came to is this,
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()
In this code, the problem I'm getting is
Is there any way to get this to work?
Thanks in advance
Upvotes: 1
Views: 899
Reputation: 101072
Don't use threads (you don't need them), don't use pygame.time.wait
, and don't use pygame.mixer.music
if you don't want to use it for background music.
Use a Sound
object (and maybe provide a maxtime
if you want to it's play
function).
So your code should look more like this:
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)
...
Upvotes: 1