mmartins
Posts: 3
Joined: Wed Aug 17, 2016 3:39 am

Using buttons and audio for a Q/A script

Thu Dec 01, 2016 12:19 am

I'm trying to code a Q/A script, using two buttons (yes and no) for anwsers and using audio for questions. I tried to use only IF statements, but I didn't work well, it was playing wrong audios, so now I'm using functions, but it doesn't works too, it only runs the first def but doesn't reads my buttons or dont 'enter' on my IF statements.
My code doesn't show any error, and it only plays the first audio, and my buttons are working fine, I've tried it before.
Do you guys have any idea?

Code: Select all

import pygame.mixer
from time import sleep
import RPi.GPIO as GPIO
from sys import exit
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.IN)#YES
GPIO.setup(3, GPIO.IN)#NO

pygame.mixer.init()

sndA = pygame.mixer.Sound("audio.wav")#DO you want to eat?
sndB = pygame.mixer.Sound("audio2.wav")#Ok! lets GO!
sndC = pygame.mixer.Sound("audio3.wav")#Did you finish?
sndD = pygame.mixer.Sound("audio4.wav")#Great! 
sndE = pygame.mixer.Sound("audio5.wav")#No problems!
sndF = pygame.mixer.Sound("audio6.wav")#Oh dear! ok :(
soundChannelA = pygame.mixer.Channel(1)
soundChannelB = pygame.mixer.Channel(2)
soundChannelC = pygame.mixer.Channel(3)
soundChannelD = pygame.mixer.Channel(4)

def havealunch():
	time.sleep(5)
	soundChannelA.play(sndA)#Do you want to eat?
	if (GPIO.input(2) == False):#Yes
		wants()
	elif (GPIO.input(3) == False):#No
		doesntwants()	
	time.sleep(5)
def wants():
	soundChannelB.play(sndB)#Ok! Lets go!
	time.sleep(10)
	didyoufinish()
	
def doesntwants():
	soundChannelD.play(sndF)#Oh dear! Ok :(
	
def didyoufinish():
	soundChannelD.play(sndC)#Did you finish?
	if (GPIO.input(2) == False):#Yes!
		finished()
	if (GPIO.input(3) == False):#No
		didnt()

def finished():	
	soundChannelD.play(sndD)#Great!
	
	
def didnt():
	soundChannelD.play(sndE)#No problems!	
	didyoufinish()	

print "Ready!!!"
	
while True:	
	havealunch()

		

User avatar
davef21370
Posts: 897
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: Using buttons and audio for a Q/A script

Sat Dec 03, 2016 1:12 pm

As it is the user would need to be pressing one of the buttons while the question is being asked. You need to read your button presses in a loop after asking the question thern wait for one of them to be pressed before moving on.

Dave.
Apple say... Monkey do !!

Return to “Python”