R语言玩音乐

使用帮助信息,访问:readme

---
title: "R Notebook"
output: html_notebook
---
```{r}
# 加载gm包
library(gm)
# 生成乐谱数据
# Create a flute 乐器74 长笛
flute <- Instrument(74, pan = -90)
flute
# Create a tempo
tempo <- Tempo(60, marking = "Adagio (half = 25)")
tempo
#music 
music <- 
  Music() +
  Meter(4, 4) +  # 4/4拍
  Line(c("E5","E5","E5","G5","A5", "G5", "c5", "D5")) + flute + tempo  # 音符序列
music

# 展示乐谱(生成MP3音乐、可调用MuseScore渲染并打开)
export(music,"~/x.mp3","musescore")
export(music,"~/x.mscz","musescore")

#打开网页、musescore 编辑查看乐曲
show(music,musescore = "-r 800 -T 5")

#vignette("gm") 显示帮助信息

```

更多示例代码:

---
title: "R Notebook"
output:
  pdf_document: default
  html_notebook: default
---
# R语言gm音乐包基本语法
```{r}
# 加载gm包
library(gm)
# 生成乐谱数据
# Create a flute 乐器74 长笛
flute <- Instrument(41, pan = -90)
flute
slur <- Slur(3, 8) #连音线
# Create a tempo
tempo <- Tempo(60, marking = "Adagio (half = 25)")
notehead <- Notehead(1, shape = "diamond", color = "#800080")
tie <- Tie(1) #连音 
line <- Line(
  pitches = c("E5","E5","E5","G5","A5", "G5", "c5","D5","e5","c5","g4","a4","c5","a4","g4","c-5","g#4"),
  durations = c(1, 1, 1,1,0.5,0.5 )
)
#music 
music <- 
  Music() +
  Meter(3, 4) +  # 4/4拍
  line + #声调 -降调
  flute + 
  tempo +
  notehead  +
  slur +       # lianyinfu
  tie          # 音符序列

# 展示乐谱(生成MP3音乐、可调用MuseScore渲染并打开)
export(music,"~/x.mp3","musescore")
export(music,"~/x.mscz","musescore")

#打开网页、musescore 编辑查看乐曲
show(music,musescore = "-r 800 -T 5")

#vignette("gm") 显示帮助信息

```
# example1
```{r}
# 假设 gm 支持字符串解析(否则需手动转换)
notes <- c("C4", "E4", "G4", "C4","E4","E4","E4","G4","A4", "G4")
# 转换为 MIDI 编号(手动映射)
instrument= Instrument(77)
note_to_midi <- function(note) {
  notes_map <- list(
    C4 = 60, Cs4 = 61, D4 = 62, Ds4 = 63, E4 = 64, F4 = 65,
    Fs4 = 66, G4 = 67, Gs4 = 68, A4 = 69, As4 = 70, B4 = 71
  )
  notes_map[[note]]
}
pitches <- sapply(notes, note_to_midi)
pitches
music<- Music() +
        Meter(3, 4) +   # 4/4拍
        Line(pitches)+
        instrument

show(music)
```
# example2 混合时值,不同乐器
```{r}
pitches <-c(67, 67, 67, 62, 65, 67, 69, 67)
durations <- c(0.5, 0.5, 1, 2, 0.5, 0.5, 1, 2)   # 八分+八分+四分 / 二分 / ...
tempo = Tempo(120)
velocity = Velocity(100)  #力度
riff <-Music()+ 
  Meter(3,4)+
  Line(pitches,durations) +
  tempo+ 
  velocity

export(riff, "~\\riff.mid")
show(riff)
```
# example3 简单旋律

```{r}
library(gm)

# 定义时值(全部为四分音符)
instrument = Instrument(41) #小提琴
tempo= Tempo(90)
line <- Line(
  pitches = c(60, 62, 64, 65, 67, 69, 71, 72,73,69, 71, 72,73) , 
  durations = c(1, 1, 1.5, 0.5,1)
)
# 创建音乐线条
melody <- 
  Music() +
  Meter(4, 4) +   # 4/4拍
  line +
  instrument + 
  tempo          # 音符序列

# 播放或导出
#show(melody,musescore = "-r 800 -T 5") 
show(melody) # 如果有音频输出支持
export(melody, "~/scale.mid","musescore")

```