# Recursion Lab Solutions # Fall 2020 # recursiveDrums.py from synth import * #--------# # Task 1 # #--------# def drumBeats(number, duration): """ Adds the given number of drum beats to the given track, each with the given duration. Uses recursion to do this instead of a loop. """ if number > 0: addBeat(duration) drumBeats(number - 1, duration) #--------# # Task 2 # #--------# def spacedBeats(number, duration): """ Starting at the given start time, adds the given number of beats of the given duration to the current track, with rests between them that are twice as long as the beats. There is no rest after the last beat. """ if number > 1: addBeat(duration) addRest(duration*2) spacedBeats(number - 1, duration) elif number > 0: addBeat(duration) #--------# # Task 3 # #--------# def decreasingBeats(number, duration): """ Adds the given number of beats to the current track, where the first beat added has the given duration, but each subsequent beat is only 3/4 as long as the beat before it. """ if number > 0: addBeat(duration) decreasingBeats(number - 1, duration*0.75) #--------# # Task 4 # #--------# def squeezeBeats(duration, minDuration): """ Adds a pair beats of the given duration to the given track, and in between those, adds another pair with 3/4 the duration of the outer pair, and so on, until the duration would be less than or equal to the given minimum duration. """ if duration > minDuration: # Add initial beat addBeat(duration) # Add recursive beats short = duration * 0.75 squeezeBeats(short, minDuration) # Add final beat addBeat(duration) #--------# # Task 5 # #--------# def layeredBeats(duration, complexity): """ Adds a pattern of layered beats at the given start time which lasts for the given duration. For each complexity level, another set of beats will be layered on top, and each layer fits one more beat than the previous one within the given duration. The current time is set to the end of the whole layered beats section when the function is done. """ if complexity == 1: addBeat(duration) # note that we don't rewind here else: # Compute the duration of the shorter beats eachDuration = duration / complexity # Add multiple drum beats using our earlier function drumBeats(complexity, eachDuration) # Rewind so that the next layer will overlap this one rewind(duration) # Add more layers layeredBeats(duration, complexity-1) #--------------# # Testing code # #--------------# if __name__ == "__main__": print("Start of testing...") drumBeats(4, 0.2) drumBeats(8, 0.1) addRest(0.5) spacedBeats(4, 0.2) #addRest(0.5) #decreasingBeats(8, 0.4) #addRest(0.5) #squeezeBeats(0.2, 0.05) #addRest(0.5) # Prints out a description of each note printTrack() # Saves the track as "recursive.wav" saveTrack("recursive.wav") # Plays the track (only works if simpleaudio library is available) playTrack() print("...done testing.")