Randomly Generating Music with R
Apr 19, 2021
Beyond single-cell analysis, coding in
R is a useful skill for lots of other fun things too :D
Here, I use the
gm by Renfei Mao to generate a random song.
## install.packages("gm") library(gm)
To generate my random song, I will select from a corpus of possible major chords.
## chords notes <- list( c('C4', 'E4', 'G4'), ## C major c('D4', 'F#4', 'A4'), ## D major c('E4', 'G#4', 'B4'), ## E major c('F4', 'A4', 'C4'), ## F major c('G4', 'B4', 'D4'), ## G major c('A4', 'C#4', 'E4'), ## A major c('B4', 'D#4', 'F#4') ## B major )
I will randomly sample 3 chords and repeat the second chord to create a 4 chord melody. I will also repeat the 4 chords for the refrain. I do this twice to compose the general song.
## sample random notes set.seed(100) progn1 <- sample(notes, 3, replace=FALSE) progn2 <- sample(notes, 3, replace=FALSE) ## song notes songn <- c(progn1, progn1, ## repeat progn1, progn1, progn2, progn2, ## repeat progn2, progn2)
Instead of just a progression of chords, I will have one line of half notes, and one line of eighth notes where I break up the chord into its 3 notes, repeating a note for 4 notes per chord.
## split into two lines bgn <- songn bgd <- as.list(rep("half", length(bgn))) mainn <- as.list(unlist(lapply(songn, function(x) c(x, x, x, x)))) maind <- as.list(rep("eighth", length(mainn)))
Now, let’s see what this song sounds like!
## make music m <- Music() + Meter(4, 4) + Line(pitches = mainn, durations = maind) + Line(pitches = bgn, durations = bgd) show(m + Tempo(120), to = c("score", "audio"))
It’d be even more fun to train a generative adversarial neural network or other deep learning model on say the top Billboard or jazz melodies to generate new songs, but perhaps that will be left to a more ambitious and motivated student :)
Try it out for yourself and see what you can come up with!
For more creative coding, check out of some my other fun products:
- Randomly Generating Music with R on 19 April 2021
- Animating the Cell Cycle on 28 December 2020
- Using R To Find The Missing Faculty on 30 November 2020
- Using scVelo in R using Reticulate on 25 August 2020
- A Guide to Responding to Scientific Peer Review on 17 June 2020
- Quickly Creating Pseudobulks on 06 April 2020
- A Guide to Scientific Peer Review on 23 March 2020
- Ten PhD Transition Tips for the Biological Sciences on 23 January 2020
- RNA Velocity Analysis (In Situ) - Tutorial and Tips on 14 January 2020
- How to write an abstract on 24 September 2019