我正在尝试创建一个鼓小程序。因此,鼓的每个部分都有相应的键盘键,如果按下它,会播放声音。如何使用按键播放声音?
答案 0 :(得分:0)
好。所以你需要不同鼓组声音的样本,例如。 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){}
}
希望这有助于您理解。