用命令行写音乐🎶
· 阅读需 3 分钟
我最近萌生了用代码写音乐的想法🎶,用ai找了一轮后,看到了如下几个:
我还没用devalang,strudel倒是写出来了。
用JavaScript写音乐🎶
还挺好玩的,给ai描述需要的音色和节奏,让它构建基础,然后根据自己的审美来调整,边做边看它闪来闪去很好玩。

做出来是这样的。
(听久了会有点烦,注释掉旋律变成沙发音乐就很泛用😊)
不过它并不能直接导出音频或者midi,需要接入daw或者用Tenacity,Tenacity录音很好用,而且很小只有55.8mb。
在strudel用到的代码,复制后扔进strudel就能播了。嫌旋律太吵注释或者删掉就好了,注释掉就是个Em9的进行。
setcpm(40)
stack(
// 鼓组:底鼓 + 小鼓 + 踩镲,踩镲随机静音
s("bd*2 [~ sd] bd [~ sd]")
.gain(0.9),
s("hh*8").gain(0.35).pan("0.3 0.7")
.sometimes(x => x.gain(0)),
// 贝斯:前八后十六,E 小调线条
note("<e2 e2 g2 d2>")
.s("sawtooth")
.lpf(400)
.gain(0.6)
.struct("x ~ x x")
.release(0.1)
.sometimes(x => x.transpose(12)),
// 和声:省略五音的九和弦,E Dorian 调性
note("<[e3,g3,d4,f#4] [c3,e3,bb3,d4] [d3,f#3,c4,e4] [b2,d3,a3,c#4]>")
.s("triangle")
.attack(0.05)
.release(0.4)
.lpf(sine.range(600, 2000).slow(4))
.gain(0.25)
.room(0.6),
// 氛围 Pad:电声长音,慢速滤波,随机音高偏移
// 氛围 Pad:中音区,电声,短促切分
note("<[e3,g3,b3] [c3,e3,g3] [d3,f#3,a3] [b2,d3,f#3]>")
.s("square")
.struct("x ~ x x ~ x ~ x")
.attack(0.02)
.release(0.15)
.lpf(sine.range(800, 2000).slow(6))
.shape(0.25)
.gain(0.16)
.room(0.45)
.delay(0.4)
.pan(sine.range(0.3, 0.7).slow(6))
.sometimes(x => x.transpose(12))
.sometimes(x => x.struct("x ~ x x ~ ~ x x"))
.sometimes(x => x.struct("x x ~ x ~ x x ~")),
// Lead 旋律线:电声小号质感,E Dorian ,随机动态
n("0 [2|1] 4 7 4 [2|1] 0 ~")
.scale("d4:melodicminor")
.slow(2)
.s("sawtooth").shape(0.8)
.lpf(rand.range(600, 3000))
.attack(0.03)
.release(0.25)
.gain(0.08)
.velocity(rand.range(0.5, 1))
.delay(0.35)
.room(0.5)
.sometimes(x => x.transpose(12))
.sometimes(x => x.fast(2))
.sometimes(x => x.rev())
.every(4, x => x.add(note("0 3 5"))),
// 电萨克斯:E小调五声和F#小调五声随机,切分+三连音,动态变化
n("0 2 3 4 3 2 0 ~ 0 2 3 5 4 3 2 ~")
.scale("e5:minor|f#5:minor")
.scramble(16)
.struct("x ~ x [x x x] ~ x ~ x x ~ x [x x] ~ x")
.sometimes(x => x.struct("x ~ x x ~ x ~ x x ~ x ~ x x ~ x"))
.sometimes(x => x.struct("x ~ x [x x] ~ x ~ x x ~ x [x x] ~ x"))
.s("sawtooth").shape(0.7)
.lpf(sine.range(1500, 3500).slow(3))
.attack(0.04)
.release(0.35)
.gain(0.22)
.velocity(sine.range(0.5, 1).slow(3))
.delay(0.5)
.room(0.6)
.sometimes(x => x.transpose(12))
.sometimes(x => x.degradeBy(0.15))
.mask("<0 0 [1|0] 1>/4"),
)
我本来想写E dorian b2音阶作为旋律,可是strudel不支持,换算成D旋律小调也不支持,最后作罢只能用E dorian。