'''
Created on 23 Apr 2016

@author: Alex Burn

Jukebox plays music over a Raspberry Pi's GPIO pin to a connected speaker
'''

import RPi.GPIO as GPIO
from time import sleep

def play(music, pin):
    '''
    Plays music over the given GPIO pin. 
    music parameter is a 2d list, which is a list of pairs of values. Each pair is of the form [Frequency(Hz), Duration(ms)]
    '''
    speed = 1 #Can be changed to alter the playback speed
    #GPIO Configuration    
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(pin, GPIO.OUT)

    #Loop through music
    for i in range(len(music)):
        print(len(music))
        frequency=music[i][0]
        duration=music[i][1]/(1000.0*speed) #Convert time in ms to seconds
        print(frequency,duration)
        if(frequency==0):
            sleep(duration)
        else:
            duration=music[i][1]/(1000.0*speed)
            period = 1.0 / frequency    
            half_period = period / 2   
            cycles = int(duration * frequency) #Number of wave cycles in the given duration
            
            #Play frequency for this many wave cycles
            for c in range(cycles):
                GPIO.output(pin, 1) 
                sleep(half_period)
                GPIO.output(pin, 0)
                sleep(half_period)
            