I needed to make a simple thing and it seemed like a good starter project to learn python. I followed this GPIO music box tutorial (https://projects.raspberrypi.org/en/projects/gpio-music-box) and it runs fine in MU, Thonny Python IDE, but when I run on Geany it will open in a terminal, run end, produce no sound on button push. What I need is for this script to start automatically once raspbian is booted up and play back sounds at start. I've tried editing rc.local, bashrc, and crontab for automatic startup.
So this is running on a pi3 and the script looks like this basically:
import pygame from
gpiozero import Button
pygame.init()
drum = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/drum_tom_mid_hard.wav")
cymbal = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/drum_cymbal_hard.wav")
snare = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/drum_snare_hard.wav")
bell = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/drum_cowbell.wav")
btn_drum = Button(4)
btn_drum.when_pressed = drum.play
Is this not working because when the script is run in a terminal it doesn't import this python library? My only other experience programming is simple projects C# on Crestron units.
Thanks
A program run in terminal will terminate once it has executed all the code. If you want a program that passively sits and listens for user inputs, you need to add a loop to keep the program running. The basic structure looks like this (taken from https://realpython.com/pygame-a-primer/#setting-up-the-game-loop)
# Variable to keep the main loop running
running = True
# Main loop
while running:
# Look at every event in the queue
for event in pygame.event.get():
# Did the user hit a key?
if event.type == KEYDOWN:
# Was it the Escape key? If so, stop the loop.
if event.key == K_ESCAPE:
running = False
# Did the user click the window close button? If so, stop the loop.
elif event.type == QUIT:
running = False
If this structure is not familiar to you, the idea is that as long as the variable running = True, the program will keep going back to the while line every time it reaches the end. When you do want to end the program, such as allowing a user to press the escape key to quit, you add an event listener as shown that changes the running variable to false.
If I'm understanding your problem right, put all your initializations and imports at the beginning of the script, then all your event listeners in the loop. I highly recommend reading through the pygame documentation as well.