# A function to create a sound collage

def soundCollage(sound1, sound2, sound3):
  
  # normalise the sounds
  sound1 = normalise(sound1)
  sound2 = normalise(sound2)
  sound3 = normalise(sound3)

  #take snips from the sounds
  sound1 = getSection(sound1, 0.001, 1.0)
  sound2 = getSection(sound2, 0.001, 0.09)
  sound3 = getSection(sound3, 0.01, 1.0)

  collageSound = makeEmptySound(10) #make a 10 second empty sound to place the sounds in
  
  #copy the snips into the collage sound
  i = 1
  for s in range(1, getLength(sound1)):       
    currentsample = getSampleValueAt(sound1, s)
    setSampleValueAt(collageSound, i, currentsample)
    i = i + 1
  for s in range(1, getLength(sound2)):        
    currentsample = getSampleValueAt(sound2, s)
    setSampleValueAt(collageSound, i, currentsample)
    i = i + 1
  for s in range(1, getLength(sound3)):        
    currentsample = getSampleValueAt(sound3, s)
    setSampleValueAt(collageSound, i, currentsample)
    i = i + 1
  
  # play the collage
  play(collageSound)

  # return the final sound
  return collageSound

# Recipe 54: Normalise the sound to a maximum amplitude

def normalise(sound):
  largest = 0
  for s in getSamples(sound):        
    largest = max(largest,getSample(s))
  amplification = 32767.0 / largest

  for s in getSamples(sound):      
    louder =  amplification * getSample(s)  
    setSample(s, louder)  

  return sound  


# A function to get a section of a sound

def getSection(sound, start, end):
  
  startsample = int(start*(float(getSamplingRate(sound)))) #start position
  endsample = int(end*(float(getSamplingRate(sound)))) #end position
  sectionsound = makeEmptySound(int(end-start)+1)#create empty sound for the given section

  #extract the sample in the given section and place into sectionsound
  i = 1
  for sample in range(startsample, endsample): 
    currentsample = getSampleValueAt(sound, sample)
    setSampleValueAt(sectionsound, i, currentsample)
    i = i + 1

  #return the taken section
  return sectionsound
