Tone.js基础使用

1.tone的调试

按照官网的调试方法,直接在js里写入:

1
2
3
import * as Tone from 'tone' // 导入包,必要
const synth = new Tone.Synth().toDestination(); // 连接到电脑音频
synth.triggerAttackRelease("C4", "8n"); // 发出声音

而不用加上react里面的组件和渲染,浏览器就可以发出声音。


2.tone的基础使用

tone里面有一个now常量,如果像下面这样写,就会一直发出声音不停。

1
2
3
4
const synth = new Tone.Synth().toDestination();
const now = Tone.now()
synth.triggerAttack("C4", now)
// synth.triggerRelease(now + 1) 把这行加上就会在下一个拍结束

这个Attack和Release可以结合到一起,写起来比较方便。而且时刻不能重叠,重叠就只会发出最后一个声音。

1
2
3
4
5
const synth = new Tone.Synth().toDestination();
const now = Tone.now()
synth.triggerAttackRelease("C4", "8n", now)
synth.triggerAttackRelease("E4", "8n", now + 0.5)
synth.triggerAttackRelease("G4", "8n", now + 1)


3.tone计时和多音轨

tone可以提供一个计时器,从页面加载开始计时。

1
setInterval(() => console.log(Tone.now()), 100);

tone可以双音轨。下面的例子给出音轨中tone自身的循环(不需要setInterval),而且循环内部越来越快。如下:

1
2
3
4
5
6
7
8
9
10
11
const synthA = new Tone.FMSynth().toDestination(); // 两个音轨
const synthB = new Tone.AMSynth().toDestination();
const loopA = new Tone.Loop(time => { // 里面这个箭头函数写法固定
synthA.triggerAttackRelease("C2", "8n", time); // 创建循环,其中C2的长度是八分音符,每个C2之间的间隔
}, "4n").start(0); // 是四分音符,从0开始(下面是从第一个八分音符的位置开始)
const loopB = new Tone.Loop(time => {
synthB.triggerAttackRelease("C4", "8n", time);
}, "4n").start("8n");
Tone.Transport.start() // 开始Transport
Tone.Transport.bpm.rampTo(800, 5); // 将原来频率在五秒内调整到800
Tone.Transport.stop(10) // 发声10秒后停止

tone提供了三个音轨,分别是Tone.FMSynth, Tone.AMSynth 和 Tone.NoiseSynth。这三个音轨都是一个时间点只能由一个音的。如果想要多个音在同一时间发出,就要用到Tone.PolySynth。例子如下:

1
2
3
4
5
6
7
8
const synth = new Tone.PolySynth(Tone.Synth).toDestination();
const now = Tone.now() // 这里试验过,这个now一定跟在这个synth一个域下,不然会出问题
synth.triggerAttack("D4", now);
synth.triggerAttack("F4", now + 0.5);
synth.triggerAttack("A4", now + 1);
synth.triggerAttack("C5", now + 1.5);
synth.triggerAttack("E5", now + 2);
synth.triggerRelease(["D4", "F4", "A4", "C5", "E5"], now + 4); // release接收数组将多个音全都释放

4.tone播放MP3

tone可以播放MP3。例子:

1
2
3
4
const player = new Tone.Player(url).toDestination();
Tone.loaded().then(() => {
player.start();
});

根据tone可以播放mp3的特性,可以将新的音阶加入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const sampler = new Tone.Sampler({
urls: {
"C4": "C4.mp3",
"D#4": "Ds4.mp3",
"F#4": "Fs4.mp3",
"A4": "A4.mp3",
},
release: 1,
baseUrl: "https://tonejs.github.io/audio/salamander/",
}).toDestination();

Tone.loaded().then(() => {
sampler.triggerAttackRelease(["Eb4", "G4", "Bb4"], 4); // 这里的4是延长的时间
})

tone还有音乐特效。我感觉用不到就不写出例子了。