Raspberry pi audio playback with pygame

Raspberry pi audio playback with pygame

Postby mrkirkby » Thu Sep 01, 2016 9:39 pm

Hello! I'm looking for a bit of help with a piece of code I'm writing.

I'm using python 3 on the raspberry pi. I'm new to python but have experience in C. To make things a little bit more understandable while debugging I've commented out and set up a little bit like an arduino program.

What's not working for me though is the fact I've put in a way of trapping whether or not pygame.mixer is running a bit of audio or not and the code seems to allow a button press on gpi regardless which re-starts playback.

My intention is to have one single file play to its end, then allow the button to trigger the file again. Think a big button members of public can press in order to make a sound file play once. It's have it re-fire or fire multiple instances if a kid keeps pressing it.

Here's my code as it stands:

Code: Select all
# Pi GPIO Music player
# By Andrew
# 1st September 2016
# Version 0.1
# __________________
# ______NOTES_______
# Imports

from gpiozero import Button
from signal import pause
import pygame.mixer
from pygame.mixer import Sound
pygame.mixer.init(frequency=44100, size=16, channels=2, buffer=4096)

# Setup
def setup():
    global button
    global button2
    button = Button(2)# Define button 1
    button2 = Button(3) # Define button 2
    global busyCh # Variable to see if sound is running
    pygame.mixer.music.load('files/1.wav') #load the file
    pygame.mixer.music.set_volume(1.0) # Set the volume to 100%

# Loop
def loop():
    global busyCh
    print("main loop")
    button.when_pressed = pygame.mixer.music.play

# Main   
while True:
    busyCh = pygame.mixer.music.get_busy()
    button2.when_pressed = pygame.mixer.music.stop
    if busyCh==0:

Last edited by Yoriz on Thu Sep 01, 2016 9:41 pm, edited 1 time in total.
Reason: First post lock.
Posts: 1
Joined: Thu Sep 01, 2016 9:22 pm

Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest