0

I was following this guide to learn how to trigger sound with the GPIO input.
What I learned is that there is some latency between the press of the button and the played sound. Is it possible to play the sound immediately? Like reading it into a buffer and play from there?
If yes, what is the best practice to achieve this result? I am working with a Pi 2B, language can be anything, I am flexible. Any guideance is appreciated.

To be more specific, this is the Python code I ended up with:

import pygame.mixer
from pygame.mixer import Sound
from gpiozero import Button
from signal import pause

button = Button(3)
pygame.mixer.init()
sDob=pygame.mixer.Sound('mintak2/drum_tom_lo_soft.wav')
while True:
    button.when_pressed = sDob.play

There is around half second latency between the press of the button and the play of the sound.

0

No need to constantly assigned the when_pressed attribute (that'll actually cause a lot of work behind the scenes). Simply assign it once, then execute pause() to leave the script waiting on termination (i.e. Ctrl+C):

import pygame.mixer
from gpiozero import Button
from signal import pause

pygame.mixer.init()
button = Button(3)
sDob = pygame.mixer.Sound('mintak2/drum_tom_lo_soft.wav')
button.when_pressed = sDob.play
pause()

As you've also noted in your comments, you can also tweak the pygame mixer defaults, so the complete script would look like this with your fix in it:

import pygame.mixer
from gpiozero import Button
from signal import pause

pygame.mixer.pre_init(
    frequency=22100, size=-16, channels=2,
    buffersize=64)
pygame.mixer.init()
button = Button(3)
sDob = pygame.mixer.Sound('mintak2/drum_tom_lo_soft.wav')
button.when_pressed = sDob.play
pause()

(I added keyword args for readability)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.