Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use R to create music (note-by-note), such as via MIDI or another format?

Tags:

r

playback

I'm trying to use R to make music. I've found:

  1. Package musicmakeR, which is broken.

  2. Package audio, which is more for manipulating/playing existing audio files.

  3. Package tuneR.

I THINK tuneR can do everything I want to do, and I found this post (Is it possible to code music in R and play it back? (Mac OS X)). The first response in that post (from 'rakshith1124') seems to answer my question, but either I'm coding something incorrectly or there's an issue with my OS or .wav player. Here is the code I'm using:

library(tuneR)

sr <- 8000
bits <- 16
secs <- 1
amp <- 1
t <- seq(0, secs, 1/sr)

C0 <- 16.35
G3 <- 196
A5 <- 880

C0 <- floor(2^(bits-2)*(amp*sin(2*pi*C0*t)))
G3 <- floor(2^(bits-2)*(amp*sin(2*pi*G3*t)))
A5 <- floor(2^(bits-2)*(amp*sin(2*pi*A5*t)))

u <- Wave(c(C0,G3,A5), samp.rate=sr, bit=bits)

play(u)

This should play three notes (C0, G3, A5) for one second each. I got the frequencies of the notes from https://pages.mtu.edu/~suits/notefreqs.html. The .wav played by the script [play (you)] seems to be truncating the first note or something else I don't understand. Does anyone know what's going on, and relatedly, is there a better package to be using for music creation?

like image 575
Tyler Moore Avatar asked Oct 16 '18 14:10

Tyler Moore


1 Answers

The R package "gm" is designed for creating music. A "Hello! World" example:

library(gm)

m <- 
  # initialize a Music object
  Music() +
  # add a 4/4 time signature
  Meter(4, 4) +
  # add a musical line of four quarter notes
  Line(list("C5", "D5", "E5", "F5"), list(1, 1, 1, 1))
  
show(m)

output musical score

You can check its complete guide for more examples. It generate musical scores and audio files in R Markdown documents, Jupyter Notebooks, RStudio.

I am the author of the package (I am asked to disclose my affiliation with the suggested solution).

like image 135
flujoo Avatar answered Sep 28 '22 15:09

flujoo