Map Functions

Map functions are used anytime you want to convert data from one range to another. This is a common task in computer music composition, but also when building GUI applications.

For convenience, map functions are included in the music library, so, in order to use them, you need the following in your program:

Two functions are provided:

 


mapValue()

mapValue() converts a value from one numeric range to another.

Function Description
mapValue(value, minValue, maxValue, minResult, maxResult) Takes a number within one range and returns its equivalent within another range. The arguments are:

  • value – the number to be mapped
  • minValue – the lowest possible number to be mapped (inclusive)
  • maxValue – the highest possible number to be mapped (inclusive)
  • minResult – the lowest value of the destination range (inclusive)
  • maxResult – the highest value of the destination range (inclusive)

For example, mapping the value 0 from the range 0..100 to the range 10..20 results in 10:

Notice how 0 is the leftmost value in its range, as is 10.

Similarly, mapping 50 from the range 0..100 to the range 10..20 results in 15:

Again, notice how 50 is in the middle of its range, and so is 15.

So, mapValue() maintains the relative position of a value.

 


mapScale()

mapScale() is similar to mapValue() except, in addition, it forces (quantizes) the output to fit a particular scale. In other words, is the numeric result does not fall in the pitches of the provided scale, it is rounded to the closest scale pitch.

This is very useful for music applications, where the outcome is used to generate a melody.

Function Description
mapScale(value, minValue, maxValue, minResult, maxResult, scale) Takes a number (i.e., MIDI pitch) within one range and returns a its equivalent within another range, quantized to the pitch class value in scale. The arguments are:

  • value – the number to be mapped
  • minValue – the lowest possible number to be mapped (inclusive)
  • maxValue – the highest possible number to be mapped (inclusive)
  • minResult – the lowest value of the destination range (inclusive)
  • maxResult – the highest value of the destination range (inclusive)
  • scale – (optional) the musical scale (a list of pitch classes between 0 and 11) to be applied to the destination range (here are common scales).  If omitted, mapScale() works like mapValue().
  • key – (optional) the key of the scale (0 means C, 2 means D, and so on). Default is minResult, the lowest value of the destination range.

For example, using mapValue() to map 50 from the range 0..100 to the range 10..20 results in 15:

However, using mapScale() with MAJOR_SCALE in the key of C, the result is 14:

This is because 15 is not part of the major scale starting at 0 (default), whereas 14 is (i.e., it’s the second scale degree, D, since 12 is the octave, C).