将音乐添加到我的声卡项目中

时间:2015-05-26 14:41:55

标签: java audio

所以我正在使用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);


    }

}

1 个答案:

答案 0 :(得分:2)

播放声音有很多不同的方法,但例如你可以这样做:

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文件没有问题,我认为它也会播放其他类型的声音文件,但我不确定它将播放哪种声音类型以及它不会播放哪些声音类型。

我希望这有帮助:)

编辑:

正如您所看到的,可以从此代码中抛出许多异常,因此您可能希望以适当的方式处理它们。