因此,我正在使用Java为CS项目创建音板。音板由8个鼓组组成,应在单击时播放其设定的声音。我已经设置了要单击的区域,但是不知道如何实现单击设置区域时将开始的声音。
// FinalProjectst.java
// AP Computer ScienceStudent Version
import java.awt.*;
import java.applet.*;
import java.awt.geom.Ellipse2D;
public class FinalProjectst extends Applet
{
Image picture;
Ellipse2D base, bT, snare, lT, rT, hh, lC, rC;
int numColor;
public void init()
{
picture = getImage(getDocumentBase(),"drumSet.jpg");
base = new Ellipse2D.Double (355, 415, 305, 240); //Bass
bT = new Ellipse2D.Double (715, 360, 325, 245); //Bottom Tom
snare = new Ellipse2D.Double ( 35, 410, 290, 200); //Snare
lT = new Ellipse2D.Double (283, 130, 185, 165); //Left Tom
rT = new Ellipse2D.Double (543, 120, 200, 175); //Right Tom
hh = new Ellipse2D.Double ( 0, 225, 250, 150); //High Hat
lC = new Ellipse2D.Double ( 10, 0, 305, 195); //Left Cymbal
rC = new Ellipse2D.Double (765, 0, 505, 275); //Right Cymbal
}
public boolean contains(Event e, int x, int y)
{
if(base.contains(x,y))
numColor = 1;
else if(bT.contains(x,y))
numColor = 2;
else if(snare.contains(x,y))
numColor = 3;
else if(lT.contains(x,y))
numColor = 4;
else if(rT.contains(x,y))
numColor = 5;
else if(hh.contains(x,y))
numColor = 6;
else if(lC.contains(x,y))
numColor = 7;
else if(rC.contains(x,y))
numColor = 8;
else
numColor = 9;
repaint();
return true;
}
public void paint(Graphics g)
{
g.drawImage(picture, 0, 0, this);
}
}
最佳答案
播放声音的方式有很多,但是例如您可以执行以下操作:
public static void playSound(File soundfile) throws LineUnavailableException, UnsupportedAudioFileException, IOException{
AudioInputStream audioInputStream = null;
audioInputStream = AudioSystem.getAudioInputStream(soundfile);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}
这段代码可以毫无问题地播放wav文件,我认为它也可以播放其他类型的声音文件,但是我不确定它将播放什么声音类型以及不会播放什么声音类型。
我希望这个帮助:)
编辑:
如您所见,此代码可以引发很多异常,因此您可能希望以适当的方式处理它们。