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

2

5

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?

Humblebee answered 16/10, 2018 at 14:48 Comment(1)
This question shows an example of how to set up music. #31783080Paradiddle
C
7

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).

Condone answered 23/3, 2021 at 12:21 Comment(1)
Does anyone got the error Error in magick_image_write(image, format, quality, depth, density, comment, : rsession: NegativeOrZeroImageSize ' @ error/image.c/CloneImage/794?Quaternion
S
4

Cool question!

The code reproduces perfectly on my machine — including that strange "truncated" sound in the beginning. Why is that correct? The issue is that your speaker / soundcard / player cannot reproduce frequencies that are as low as 16 Hz (that's really low). The other notes after C0 seem fine.

See also this question on SE electronics.

Spermatozoid answered 16/10, 2018 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.