Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Haskell
Wiki community
Recent changes
Random page
HaskellWiki
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
The Monad.Reader/Issue2/Haskore
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
= Haskore = This Article will be about [[Haskore]], which is a Haskell library for describing music. It follows an approach of describing a domain specific language and thus reduces complications of arbitrary language decisions. Imagine, for example, a structure describing Music in any imperative language and compare this to the simplicity of a Haskore representation. A core of the Haskore system is Score data, which is stored as a Type called <code>Music</code>. Score data is usually represented like this: attachment:haskore1-ex1.gif This sequence of Symbols, while looking relatively simple to the musician's eye, gives us a lot of information about the music we associate with it. Some of the information encoded here would be the number of notes struck, their lengths, how they overlap or don't. Implicitly, we assume that we're dividing an octave into 12 "halftones" (look at the numeric values of (12th root of 2)^''n'' for ''n''=0...12 and compare to "simple" fractions to gain understanding of the significance of this number: ''n''=7 is the "fifth" (c-g), ''n''=4 the "major third", ''n''=3 the "minor third" etc.), that a certain note called "a" represents 440 oscillations per second and a few other, even more arcane things. We shall see that we need to give our computer all this information to reproduce the music that we associate with these notes. == Preparation == Get [attachment:tmr-Haskore.tar.gz Haskore]. This version of Haskore is ancient but stable. I corrected it slightly to account for features that changed in the meanwhile. Unpack the file. It provides some documentation and the Haskore sources. To use Haskore interactively, change to <code>Haskore/Src</code> and start <code>hugs</code> (you could also use <code>ghci</code>, but be sure to put the file <code>Haskore/ghc_add/IOExtensions.lhs</code> into the <code>Haskore/Src</code> Directory before.) Type <code>:l HaskoreLoader</code> and <code>:m Basics</code> to initialize Haskore for immediate Experimentation. <code>:l example</code> will load Haskore, some declarations in the examples in this text, and import <code>TestHaskore</code> which will save us some time and brains by defining reasonable defaults for some features. Follow-ups of this article will need CSound. Most distributions of operating Software will allow for a relatively easy installation. == Building blocks of Music == Haskore offers a data type called <code>Music</code> that represents - as you might have guessed - music. The "atoms" of music, notes, can be generated by giving their "pitch class" (This is where the implicit assumption that our octave is divided into 12 pitches shows up) , octave, duration, and a List of Attributes , like in: <code>#!syntax haskell Basics> :t (c 1 (1%4) []) c 1 (1 % 4) [] :: Music </code> This snippet would represent a "c4" note, played for a fourth measure. The infix operator <code>%</code> is used to create a rational number. This way we can easily specify triplets, for example, which are harder in inherently quantized environments. The names Haskore gives to the "pitch classes" are, as one would expect, the names used in the Anglo-Saxon languages, that are, <code>a b c d e f g</code>. Sharp and Flat pitches are available via <code>as</code> and <code>af</code>, respectively. Note that this encoding is an absolute one and does not differentiate in any way among "enharmonics", like <code>es</code> and <code>f</code> Now how do we make this single note a music? We will have to combine it with other notes. There are two obvious way to do this. ||<^> attachment:haskore1-ex2.gif ||<#eeeeee> <code>:+:</code> ||<^> http://www.students.uni-marburg.de/~Zapf/haskore1-ex3.gif || = ||<^> http://www.students.uni-marburg.de/~Zapf/haskore1-ex4.gif || The sequential composition, expressed by the operator <code>(:+:) :: Music -> Music -> Music</code> results in a value that represents both values in temporal composition (I am tempted to write "played one after the other", but there is no playing going on for now, so this would be a bad idea) ||<^> attachment:haskore1-ex2.gif ||<#eeeeee> <code>:=:</code> ||<^> http://www.students.uni-marburg.de/~Zapf/haskore1-ex3.gif || = ||<^> http://www.students.uni-marburg.de/~Zapf/haskore1-ex5.gif || The parallel composition <code>:=:</code> has the same type, but composes both values to one that represents them simultaneously ("played at the same time"). Using <code>:t</code>, we can see that both Operators take two <code>Music</code> values and return a <code>Music</code> value. Using these Features and the rests (which are named <code>qnr</code>, <code>hnr</code> etc., for ''quarter note rest'', ''half note rest''), we can already construct a lot of music. Other useful operators (Actually, all the "operators" mentioned are just infix type constructors for <code>Music</code> values - see <code>Basics.lhs</code> line 34...43. The semantics of the constructed Score is to be added later) are <code>Trans :: Int -> Music -> Music</code> and <code>Tempo :: Ratio Int -> Music -> Music</code>. Use them to Transpose tunes, or to change their speed. The list at the end of each note does not seem to make much sense until now. It is intended to hold notewise attributes. For example, the Volume of a Note can be kept here, since it might be different for each single Note. <code>c 4 (1%4) [Volume 50]</code>, for example, would represent a quarter "c 4", played at "Volume 50". While we have a clear definition for "c 4" and "1%4", we don't have one for "Volume 50". This will become important now, when we want to make our music audible. == Output == What is missing now to play that music? Since there is no inherent support for Music in "Computers" (Turing-Equivalent Machines), we need to output something that a given synthesis equipment understands. A canonical choice for score data would be <code>midi</code>. The only information still missing in our <code>Music</code> Data is <code>midi</code> channel numbers. A Haskore abstraction for converting score Data to something closer to acoustical reality is a "Performance". There is a function <code>perform :: PMap -> Context -> Music -> Performance</code> that can convert <code>Music</code> to a <code>Performance</code>, given a <code>PMap</code> (a Mapping from player Names to Players) and a <code>Context</code> (which is not interesting right now, but can control how various performances will be coordinated). For example, we can turn an arbitrary <code>Music</code> Value to a <code>Performance</code> like this: <code>#!syntax haskell Main> perform (\_->defPlayer) defCon example1 [Event{eTime=0.0,eInst="piano",ePitch=48,eDur=0.5,eVol=113.5,pFields=[]}] </code> Using some default Values we nicked from <code>TestHaskore.lhs</code>. We see that the <code>Volume 100</code> note attribute was converted to an event volume of <code>113.5</code>. Considering that result, it's questionable if the default values were chosen all that wisely. Using <code>#!syntax haskell Main> perform (\_->defPlayer) defCon example2 [Event{eTime=0.0,eInst="piano",ePitch=48,eDur=0.5,eVol=113.5,pFields=[]}, Event{eTime=0.5,eInst="piano",ePitch=48,eDur=0.5,eVol=113.5,pFields=[]}, ... </code> We see that a performance is a flat list of <code>Event</code>s as opposed to a <code>Score</code> value, which is rather tree-like in structure. Now we are ready to write these events out to some musical format, for example <code>midi</code>. We needed some additional information to write out the <code>midi</code> file, namely a "patch map" to map the instrument name "piano" to the <code>midi</code> "Acoustic Grand Piano" (Instrument 1) on Channel 1. For other instruments, you could just extend the list. (For a list of instrument names, see <code>Haskore/Src/GeneralMidi.lhs</code>) <code>#!syntax haskell Main> outputMidiFile "example2.mid" (performToMidi (perform (\_->defPlayer) defCon example2) [("piano","Acoustic Grand Piano",1)]) </code> This call gives no visible output. After that, you should, however, find <code>example2.mid</code> in your current directory. Open it with your favourite (I recommend "Rosegarden" [http://www.rosegardenmusic.com/] on Unix-derivate systems) <code>midi</code> Sequencer/Editor tool, or play it back. For ease of use i put all these bits together to a function in <code>example.lhs</code> <code>#!syntax haskell Main> midiout "example2.mid" example2 </code> == Functional Music == How could functional programming help us specify music? Haskell variables can of course take <code>Music</code> values, and build other values from them, so we can for example <code>Trans</code>pose a given piece of music. We could, for example, write a function that converts a list of intervals (integers) and a <code>Music</code> value to a chord. <code>#!syntax haskell mychord intervals base = map (\n->Trans n base) intervals minor = [0,3,7] major = [0,4,7] </code> 0 is the prime, 3 the small third, 4 the large third and 7 the fifth. Now we can specify a simple chord progression: <code>#!syntax haskell example3 = (c 4 (1%4) [Volume 100]) :+: (g 4 (1%4) [Volume 100]) :+: (f 4 (1%4) [Volume 100]) :+: (c 4 (1%4) [Volume 100]) example4 = mychord major example3 </code> As we see, <code>mychord</code> works with any music value. What it can't do is building different chords on top of a sequence of notes. So: <code>#!syntax haskell example5 = (mychord major (c 4 (1%4) [Volume 100])) :+: (mychord minor (d 4 (1%4) [Volume 100])) :+: (mychord major (g 4 (1%4) [Volume 100])) :+: (mychord major (c 4 (1%4) [Volume 100])) </code> gives us a sequence with different kinds of chords. === Scale Theory === Now as one might know, different "Modes" of (European, traditional) Music use the same sequence of intervals, just starting from a different point in the sequence (<code>Mode</code>) and note (<code>Key</code>, <code>Tonic</code>). Using the Major scale as the original one: <code>#!syntax haskell > maj_skips = [2,2,1,2,2,2,1] </code> we declare a helper function <code>runsum</code>, which just sums up numbers in a list continuously. <code>#!syntax haskell runsum = scanl (+) 0 </code> Now we can declare all the scales based on the major scale in one function, and for example, have a look at the intervals of the minor scale. <code>#!syntax haskell scale kind = runsum (drop kind (cycle maj_skips)) </code> <code>#!syntax haskell Main> take 8 (scale 5) [0,2,3,5,7,8,10,12] </code> We need cycle because scales repeat all 8 "steps" (every octave). The intervals of the major scale, taken from the sixth (since we start counting with 0: 5), give the (natural or aeolian) minor scale. We declare a simple melody "step" wise, as in "steps" of a scale (the 8th step being the octave, 12 halftones, and the other steps depending on the exact scale used) <code>#!syntax haskell simplemelody = [(0,1%4),(5,1%2),(4,1%8),(3,1%8),(2,1%4),(5,1%2),(0,1%4)] </code> * Specify a value of type <code>(Ratio Int->Music)</code> and call it <code>base</code> (as it will become the base tone (''Tonic'') of our melody, if we give it an arbitrary length) * Find out how many halftones are between the base of a scale and the "step" wanted: <code>trans n = (fromInteger (scl !! n))</code> * Transpose the base note, given a length to complete it, about that amount, to get the ultimate result. <code>#!syntax haskell realize :: Int -> (Ratio Int->Music) -> (Int,Ratio Int) -> Music realize kind base (n,len) = Trans (trans n) (base len) where trans n = (fromInteger (scl !! n)) scl = (scale kind) </code> We'll write another helper, that realizes a few notes and puts them in a sequence: <code>#!syntax haskell testrealize kind base melody = allseq $ map (realize kind base) melody </code> === Making it Audible === Now we can realize our melody in an arbitrary scale, on an arbitrary base pitch, like for example: <code>#!syntax haskell Main> midiout "major.mid" (testrealize 0 (\l->(c 4 l [Volume 100])) simplemelody) Main> midiout "minor.mid" (testrealize 5 (\l->(d 4 l [Volume 100])) simplemelody) </code> in c major, and then in d minor. This task (transpose and change mode) makes a nice (and often-cursed) exercise for music students. Thanks to Haskell we were able to solve it in some 20 lines of code. Now of course we also want to describe music that's not only single-voiced. For example, we could want to describe the a'th three and four note chord in our scale: <code>#!syntax haskell tri a = [a,a+2,a+4] tet a = [a,a+2,a+4,a+6] </code> and put the chords numbered 1, 5, 4 and 1 after each other (if you ever thought you couldn't tell a ''I-IV-V-I progression'' even if you saw one, now you did), putting in a four note chord here and there, and adding an octave to the last ''I'': <code>#!syntax haskell test2d:: [[(Int,Ratio Int)]] test2d = [allength (1%2) (tri 0), allength (1%2) (tet 3), allength (1%2) (tet 4), allength (1%2) (8:(tri 0))] where allength l= map (\a->(a,l)) </code> Now we only need to map realize twice to that, and then fold twice (first in parallel, then serially) to make this a Music value. <code>#!syntax haskell rea2d kind base melody = allseq $ map allpar $ map (map (realize kind base)) melody </code> Try: <code>#!syntax haskell midiout "iivviprog.mid" (rea2d 5 (\l->(f 5 l [Volume 100])) test2d) </code> And listen to it. This would be all for this issue of TMR. If you should feel bored, try Haskore yourself. For example, you could: * Try to write an own melody, either using <code>realize</code> to later change scale, or without. * Put fitting chords along <code>simplemelody</code>, or put a melody along <code>test2d</code> * Read in some existing midi files using <code>readMidi</code> and try to analyze the resulting <code>Music</code> values. (for example, asking: are all notes in one scale? which ones aren't? what's their harmonic function?) * If you're really bored: get some sheet music and realize it in Haskore. Anyway, stay tuned for the next Issue of TMR. If you have any questions, join us on freenode (just point your IRC client to irc.freenode.net), channel #haskell, and don't hesitate to ask me. Bastiaan Zapf (freenode basti_) ---- CategoryArticle
Summary:
Please note that all contributions to HaskellWiki are considered to be released under simple permissive license (see
HaskellWiki:Copyrights
for details). If you don't want your writing to be edited mercilessly and redistributed at will, then don't submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
DO NOT SUBMIT COPYRIGHTED WORK WITHOUT PERMISSION!
Cancel
Editing help
(opens in new window)
Toggle limited content width