Sonic Pi Coding Class 003

Last week we wrote a function to set the volume based on musical dynamics like ‘ppp’ or ‘fff’

Functions can also be used to return information to us.

An example of a function that returns a value is below. Type it in and see how it works.

define :get_volume do |music_notation|
  # Write your code here to work out volume level
  # corresponding to music_notation like 'ppp'
  
  # Return the volume level like this
  # return volume_level
  
  # Or we could just return a number for this
  # example to see how it works
  return 0.1234
end

# Now write some code to use the function get_volume
my_volume = get_volume("ppp")
print my_volume

What I would like you to do is to modify last weeks function so that when you pass it a musical notation for volume, like ‘ppp’, it returns a number between 0 and 1.0 for Sonic Pi to use as part of an :amp property.

Once you have that function working, make your own piece of music up that uses this function as many times as you can!

Below is one way of achieving the task. If you are stuck, type this in yourself and then make your own piece of music up that uses this function as many times as you can!

# First, we define the function
#
# Function: get_volume
#
# Input:
#          Gets an amp level for a musical notation passed
#          in as a string.
#          Examples of musical notation: ppp, fff, mf etc
#
# Returns:
#          A number between 0 and max_amp
#
# Reference: https://en.wikipedia.org/wiki/Dynamics_(music)
#
define :get_volume do |music_notation|
  max_velocity = 127.0
  max_amp = 1.0
  velocity_ratio = max_amp / max_velocity
  
  case music_notation
  when "ppp"
    return velocity_ratio * 16
  when "pp"
    return velocity_ratio * 33
  when "p"
    return velocity_ratio * 49
  when "mp"
    return velocity_ratio * 64
  when "mf"
    return velocity_ratio * 80
  when "f"
    return velocity_ratio * 96
  when "ff"
    return velocity_ratio * 112
  when "fff"
    return velocity_ratio * 127
  else
    # Unknown music notation so return max volume
    return velocity_ratio * 127
  end
end

# This is where we start to play our music

# Use the variable my_volume to hold the volume level returned from the function get_volume
my_volume = get_volume("mf")

# Play a note and set the amp (amplifier) level to the value stored in the variable my_volume
play 80, amp: my_volume
sleep 1

# Another way we can do it is like this
play 80, amp: get_volume("fff")
sleep 1

 

Leave a Reply

Your email address will not be published. Required fields are marked *