我正在尝试创建一个鼓小程序。所以鼓的每个部分在键盘上都有相应的键,如果你按下它,就会发出声音。如何使用按键播放声音?
好的。所以你需要不同架子鼓声音的样本,例如。Kick, Snare, Hihat, crash等。最好是用.wav
格式。所以你要做的是使用Event Handling
,当一个键被按下时播放相应的音频。确保所有的音频样本都在当前项目所在的目录中。尽管写代码和做作业并不是这里要遵循的策略,我还是会写一个结构来给你解释。
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DrumApplet extends Applet implements KeyListener{
//declaring Audio variables
AudioClip kick, snare, hat_close, hat_opem, crash, tom;
@Override
public void init(){
kick = this.getAudioClip(getDocumentBase(), "kick.wav");
snare = this.getAudioClip(getDocumentBase(), "snare.wav");
//load all other audio samples
addKeyListener(this); //to detect the press of a key
}
@Override
public void paint(Graphics g){
//display message as to which key to press to play a sound
}
@Override
public void keyPressed(KeyEvent K){
char X = K.getKeyCode();
if(X == 'K')
kick.play(); //play kick.wav when K is pressed
if(X == 'S')
snare.play(); //play snare.wav when S is pressed
if(X == 'T')
tom.play(); //play tom.wav when T is pressed
if(X == 'O')
hat_open.play(); //play hat_open.wav when O is pressed
//write if statements for the rest of the Keys
repaint();
}
@Override
public void keyReleased(KeyEvent K){}
@Override
public void keyTyped(KeyEvent K){}
}