Generating music with F#

March 22, 2015

Read time 1 min

For a long time I have been fascinated with the idea of generating music programmatically. I decided to give it a go using F# and this is what I came up with. I wrote a program that generates a short melody in the key of C major. Not exactly Mozart, but it’s a start.

I created a type for notes and a Map of notes to their frequencies:

type note = C | Cis | D | Dis | E | F | Fis | G | Gis | A | Ais | B

let frequency = Map.ofList [(C, 261.63); (Cis, 277.18); (D, 293.66); 
(Dis, 311.13); (E, 329.63);(F, 349.23); (Fis, 369.99); (G, 392.00); 
(Gis, 415.30);(A, 440.00); (Ais, 466.16); (B, 493.88)]

A scale of C major can be modelled as a list consisting of the notes of the scale:

let cMajor = [C; D; E; F; G; A; B]

Creation of a melody is only picking wanted amount of notes from the scale randomly

let randomMelody () = 
    let r = System.Random()
    let length = cMajor.Length
    seq {0 .. 7} |> (fun x -> cMajor.[r.Next(0, length)])

Frequencies for the notes can be extracted and then written to wave file

        |> (fun x -> frequency.[x])
        |> Synth.writeMelody

I took code to create wav-files from Liam McClennan’s blog. All I did was wrap it in a module called Synth and created an public function that takes a list of frequencies. Here is an example output:

That’s it so far. Nothing fancy but hopefully something to build on in the future. The full source can be found on Github

Never miss a post