Learn about one way we can represent music in a coding language.
Coding Snippets:
All sprites can play sounds. Notes are generated using the play function. play accepts string arguments only (characters in quotes). An overview of the syntax for these arguments is provided below.
The Piano sprite wears a keyboard, and its keys light up as they are played. Otherwise, it behaves much like any other sprite. For example, p.fd 20 causes the Piano sprite to move.
Math and Computer Concepts:
The play function produces notes of different frequencies and durations. The code for each note is based on its name in the musical scale, which you may have learned in music class.
Each note in the octave starting with middle C is referred to by its letter name (C D E F G A B). To play the same note in a higher octave, follow it with one or more apostrophes ('). For lower octaves, follow the note's name with a comma (,). For example:
p.play "C"
middle C
p.play "C'"
C one octave above middle C
p.play "C,,"
C two octaves below middle C
Precede a note with a caret (^) to play a sharp, with an underscore (_) to produce a flat, or with an equal sign (=) to play a natural.
p.play "_C"
C flat (a.k.a., B)
p.play "^C''"
C sharp two octaves above middle C
The letters Z and z represent a musical rest.
Code longer notes by entering a number after the note: play "C2". Shorter notes can be played by entering a slash and then a number (like a fraction): play "C/2".
Combine notes inside of quotes to make a melody. You don't need spaces, but it is a good idea to separate notes by spaces, to help with readability. For example, the following are equivalent:
Combine notes as chords using brackets: p.play "[CEG]"
Activities:
Save each of the following in a folder called Music.
Write an Octave program to play all 12 notes in an octave (that is, the black keys as well as the white ones).
Write a script in which the notes are played faster and faster (i.e., using notes of shorter duration). Save your results as Accelerator.
Compose a Melody. Or, search online for sheet music to a melody of your choice, and code that. Either way, spice it up by adding chords and/or notes of different duration.
Compose a Duet by instantiating two Piano sprites. Position them so they don't overlap, and be sure to sync them before calling play. (Hint: you can play rounds by defining a melody as a variable, and instruct one sprite to rest the appropriate time before beginning the song.)