Mini-Lab: Changing Frequency

 


Introduction

The objectives of this mini-lab are to become familiar with using loops, ranges, and sample values to manipulate sounds by changing their pitch.



Halving and Doubling Frequency

  1. Copy the following function to halve the frequency of a sound. (This was discussed in class.) Run it with several .wav files and verify that it does what is expected. Use the MediaTools Sound Tool to look at the sound waves.
    
    # This function halves the frequency of the original sound
    # The new sound is twice as long, and sounds slower and deeper
    def halfFrequency(sound):
      # make a new sound with twice as many samples and same
      # sampling rate as original sound
      numSamples = getNumSamples(sound)
      samplingRate = int(getSamplingRate(sound))
      newSound = makeEmptySound(numSamples * 2, samplingRate)
    
      # Use a loop to get values from original sound, setting values in new sound
      index = 0
      for newIndex in range(numSamples * 2):
        val = getSampleValueAt(sound, int(index))
        setSampleValueAt(newSound, newIndex, val)
        index = index + .5   # Allows us to use each original sample twice
        
      # return the new sound
      return newSound
    
    

  2. Copy the following code skeleton to double the frequency of a sound. Follow the comments in the code to write the sections that are missing.
    
    # This function doubles the frequency of the original sound
    # The new sound is half as long, and sounds quicker and higher-pitched
    def doubleFrequency(sound):
      numSamples = getNumSamples(sound)
      samplingRate = int(getSamplingRate(sound))
      #Uncomment and finish the following line
      #newSound = makeEmptySound(HOW MANY SAMPLES IN NEW SOUND? WHAT IS ITS SAMPLING
      RATE?)  
    
      index = 0
      #for newIndex in range(#ADD APPROPRIATE CODE FOR THE RANGE HERE):
        # Get the sample value from the original sound... 
        # ADD A LINE OF CODE HERE
        # Set the sample value for the new sound...
        # ADD A LINE OF CODE HERE
        # Increment index appropriately...
        # ADD A LINE OF CODE HERE
      # ADD CODE HERE TO RETURN THE NEW SOUND
    
    
    

  3. Edit the comments in the doubleFrequency function:

  4. Save some of the new sounds you created, using the writeSoundTo function. (It works similarly to the writePictureTo function.)


Submit your results

  1. Submit the file you created in this mini-lab via Kit.
  2. Submit a sound, along with new versions of the sound produced by halfFrequency and doubleFrequency on Kit.