How can I play birthday with R?

I would like to play music using R. Although R may not be the best instrument for this purpose, it is a tool that I am familiar with, and it would be nice to show others its flexibility in such a joyful occasion.

How could I do this?

+71
r music
Aug 03 '15 at 8:22
source share
1 answer

If you really wanted to do this:

library("audio") bday_file <- tempfile() download.file("http://www.happybirthdaymusic.info/01_happy_birthday_song.wav", bday_file, mode = "wb") bday <- load.wave(bday_file) play(bday) 

Please note that you need to install.packages("audio") . If you already have a specific file, you need to convert it to WAV format first.

If you need something more programmable than playing a WAV file, here is the version that generates a melody from a series of sine waves:

 library("dplyr") library("audio") notes <- c(A = 0, B = 2, C = 3, D = 5, E = 7, F = 8, G = 10) pitch <- "DDEDGF# DDEDAGDD D5 BGF# E C5 C5 BGAG" duration <- c(rep(c(0.75, 0.25, 1, 1, 1, 2), 2), 0.75, 0.25, 1, 1, 1, 1, 1, 0.75, 0.25, 1, 1, 1, 2) bday <- data_frame(pitch = strsplit(pitch, " ")[[1]], duration = duration) bday <- bday %>% mutate(octave = substring(pitch, nchar(pitch)) %>% {suppressWarnings(as.numeric(.))} %>% ifelse(is.na(.), 4, .), note = notes[substr(pitch, 1, 1)], note = note + grepl("#", pitch) - grepl("b", pitch) + octave * 12 + 12 * (note < 3), freq = 2 ^ ((note - 60) / 12) * 440) tempo <- 120 sample_rate <- 44100 make_sine <- function(freq, duration) { wave <- sin(seq(0, duration / tempo * 60, 1 / sample_rate) * freq * 2 * pi) fade <- seq(0, 1, 50 / sample_rate) wave * c(fade, rep(1, length(wave) - 2 * length(fade)), rev(fade)) } bday_wave <- mapply(make_sine, bday$freq, bday$duration) %>% do.call("c", .) play(bday_wave) 

There are a few comments. The default octave for notes is Octave 4, where A4 is 440 Hz (note used to tune the orchestra). Octaves change to C, so C3 is one semitone higher than B2. The cause of the attenuation in make_sine is that without it, sound pop-ups appear when starting and stopping notes.

+205
Aug 03 '15 at 8:46
source share



All Articles