Development Tip

R을 사용하여 생일 음악을 재생하려면 어떻게해야합니까?

yourdevel 2020. 10. 8. 19:09
반응형

R을 사용하여 생일 음악을 재생하려면 어떻게해야합니까?


R을 사용하여 음악을 연주하고 싶습니다. R이이 목적에 가장 적합한 도구는 아닐 수 있지만, 제가 익숙한 도구이며 이러한 즐거운 기회에 다른 사람들에게 유연성을 보여 주면 좋을 것입니다.

어떻게해야할까요?


정말로 이것을하고 싶다면 :

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)

install.packages("audio")먼저 해야합니다 . 특정 파일이 이미있는 경우 먼저 WAV 형식으로 변환해야합니다.

WAV 파일을 재생하는 것보다 좀 더 프로그래밍이 필요한 경우 일련의 사인파에서 곡을 생성하는 버전이 있습니다.

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 A G D D D5 B G F# E C5 C5 B G A 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 a few points to note. The default octave for the notes is octave 4, where A4 is at 440 Hz (the note used to tune the orchestra). Octaves change over at C, so C3 is one semitone higher than B2. The reason for the fade in make_sine is that without it there are audible pops when starting and stopping notes.

참고URL : https://stackoverflow.com/questions/31782580/how-can-i-play-birthday-music-using-r

반응형