#! /usr/bin/env python

"""play a list of sound files, recording mouse button press"""

import os.path
import pygame
from pygame.locals import *
import pygame.mixer, pygame.time

mixer = pygame.mixer
time = pygame.time

import random

### audio files

# sampling rate:
mixer.init(16000)

# path
stimpath="."

# list
stims="""
nt3.wav
nn.wav
nt3.wav
nn.wav
nt3.wav
nn.wav
nt3.wav
nn.wav
nt3.wav
nn.wav
nt3.wav
nn.wav
nt3.wav
nn.wav
"""



def play(file):
	file = os.path.join(stimpath,file);
	sound=mixer.Sound(file)
	channel=sound.play()
	while channel.get_busy():
		time.wait(10)

def display(text):
    t = font.render(text, 1, (10, 10, 10))
    textpos = t.get_rect()
    textpos.centerx = background.get_rect().centerx
    textpos.centery = background.get_rect().centery
    background.blit(t, textpos)
    screen.blit(background, (0, 0))
    pygame.display.flip()

def clear_display():
    background.fill((250, 250, 250))
    screen.blit(background, (0, 0))
    pygame.display.flip()

def init():
	global results
	results = file('results.dat','a+');
	results.write('#\n')
	# pygame
	pygame.init()
	global screen
	screen = pygame.display.set_mode((300, 100))
	pygame.display.set_caption('Signal Detection Experiment')
	global font
	font = pygame.font.Font(None, 32)
	global background
	background = pygame.Surface(screen.get_size())
	background = background.convert()
	
def finish():
	results.close()


def save(stim,resp):
	print stim,resp
	results.write(stim + ' ' +resp +'\n')


### partie principale

init()

clear_display()

# cree la liste de stimuli
bag = stims.split()
nstim=len(bag)
random.shuffle(bag)


quitpressed = 0
n=0

while (not(quitpressed)) and (bag != []):
	stim = bag[0]
	bag = bag[1:]

	n = n+1
	display('Trial #'+str(n)+'/'+str(nstim))
        time.delay(500)

	play(stim)

        response = 0
        while not(response):
            for event in pygame.event.get():
                if event.type == QUIT:
                    quitpressed = 1
                    response = -1
                elif event.type == MOUSEBUTTONDOWN:
                    response=event.button
                
        clear_display()
	if (response>0): save(stim,str(response))
	time.delay(1000)


finish()




