processing可以弹的钢琴代码
时间: 2024-02-14 15:05:03 浏览: 23
以下是一个简单的Processing弹钢琴的示例代码,它将在屏幕上显示一些钢琴键,按下键盘上的A~G键即可弹奏对应的音符:
```
// 音符频率映射表
float[] freqTable = {
261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88
};
void setup() {
size(400, 300);
noStroke();
}
void draw() {
background(255);
// 绘制钢琴键
fill(255);
for (int i = 0; i < 7; i++) {
rect(i * 50, 0, 50, height);
}
// 按下键盘弹奏音符
if (keyPressed) {
int keyIndex = -1;
switch (key) {
case 'a':
keyIndex = 0;
break;
case 's':
keyIndex = 1;
break;
case 'd':
keyIndex = 2;
break;
case 'f':
keyIndex = 3;
break;
case 'g':
keyIndex = 4;
break;
case 'h':
keyIndex = 5;
break;
case 'j':
keyIndex = 6;
break;
}
if (keyIndex != -1) {
float freq = freqTable[keyIndex];
playSound(freq);
}
}
}
// 播放音符
void playSound(float freq) {
float duration = 1.0; // 音符持续时间
float amplitude = 0.5; // 音量
float[] waveform = new float[int(duration * 44100)];
float increment = (freq * TWO_PI) / 44100;
float angle = 0;
for (int i = 0; i < waveform.length; i++) {
waveform[i] = sin(angle) * amplitude;
angle += increment;
}
AudioOutput out = minim.getLineOut();
AudioPlayer player = new AudioPlayer(out, duration, waveform);
player.play();
}
```
代码中使用了Processing的`keyPressed`函数来检测键盘是否按下,然后根据按下的键来确定弹奏哪个音符。在`playSound()`函数中使用了Minim库来生成音频波形并播放音符。