How can I play birthday music using R? -


i play music using r. while r may not best tool purpose, tool familiar , nice demonstrate others flexibility on such joyous occasion.

how accomplish this?

if wanted 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) 

note you'll need install.packages("audio") first. if have specific file, you'll need convert wav format first.

if wanted bit more programmery playing wav file, here's version generates tune 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 <- "d d e d g f# d d e d g d d d5 b g f# e c5 c5 b g g" 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's few points note. default octave notes octave 4, a4 @ 440 hz (the note used tune orchestra). octaves change on @ c, c3 1 semitone higher b2. reason fade in make_sine without there audible pops when starting , stopping notes.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -