Computing Education - Encoding Basic Melody and Harmony
(These notes were used in a block teaching 8th Graders computer science techniques. Here we used the Overtone/Clojure package to create encodings of musical melodies and harmonies.)
Using pitch and duration representation
We can sound a note on a piano as follows
(use 'overtone.inst.piano)
(piano)
(piano)
Notes can be played with numbers (midi codes
0-127):
(piano 60)
(piano 61)
(piano 62)
(piano 61)
(piano 62)
To humanize expressions, each is encoded with
usual name:
(note :c4)
60(note :c4)
note :c#4)
61
(note :db4)
61
(note :d4)
62
Chords
This brings us to our first use of
Clojure's vector data structure useful for structuring music. Here we represent a chord using a vector
of three notes:
(def c4-minor [(note :c4) (note
:eb4) (note :g4)])
And we can play these notes as a
chord
(doseq [note c4-minor] (piano
note))
Or played as a simple arpeggio:
(doseq [note c4-minor] (piano
note) (Thread/sleep 200))
Overtone has a built-in chord function that takes a root and
type and returns a set of midi codes.
To play the sound of a chord we first define a function that
will sound a set of notes as a chord using synth piano or a sampled piano.
(defn play-chord [a-chord]
(doseq [note a-chord] (piano note)))
(use
'overtone.inst.sampled-piano)
(defn
play-chord [a-chord]
(doseq [note a-chord] (sampled-piano note)))
Here's a function to play chord changes that uses three arguments i) the
chord ii) the number of repetitions, and iii) the duration. We encode all in a vector like so:
[(chord :E3 :minor) 4 1]
(defn
play-changes [chords]
(doseq [ [chd reps dur] chords]
(loop [cnt reps]
(when (> cnt 0)
(doseq [] (play-chord chd) (Thread/sleep
(* 500 dur))
(recur (dec cnt)))))))
Two Example Songs:
This Land Is Your Land (IV I V I)
(def thisland [ [(chord :G3 :major) 4 1]
[(chord :D3 :major ) 4 1]
[(chord :A2 :dom7) 4 1]
[(chord :D3 :major) 4 1]])
All My Loving ( II V7 I VI IV II VII V)
Em A7 D Bm
Close your eyes and I´ll kiss you, tomorrow i´ll miss you,
G Em C A7
remember I´ll always be true.
Em A7 D Bm
And then while I´m away I´ll write home everyday
G A D
and I´ll send all my loving to you.
(def allmyloving
[ [(chord :E3 :minor) 4 1]
[(chord :A2 :dom7) 4 1]
[(chord :D3 :major) 4 1]
[(chord :B3 :minor) 4 1]
[(chord :G3 :major) 4 1]
[(chord :E3 :minor) 4 1]
[(chord :C3 :major) 4 1]
[(chord :A3 :dom7) 4 1]
[(chord :E3 :minor) 4 1]
[(chord :A3 :dom7) 4 1]
[(chord :D4 :major) 4 1]
[(chord :B3 :minor) 4 1]
[(chord :G3 :major) 4 1]
[(chord :A3 :major) 4 1]
[(chord :D3 :major) 5 1]
])