我写了个俄罗斯方块游戏,想在游戏中加入声音,就是落下的时候发出“丁","咚",这种声音,声音文件有了,请问该怎么,用什么类来实现

解决方案 »

  1.   

    http://www.moon-soft.com/program/WEB/javascript/article/other/27.htm
      

  2.   

    import javax.swing.ImageIcon;import sun.audio.AudioPlayer;
    import sun.audio.AudioStream;
    /**
     * 中国象棋工具类
     * 
     * 不允许被继承,不允许实例化。
     * 
     * @author 雷文
     * 
     */
    public final class ChessUtil { private ChessUtil() { }
    /**
     * 根据名字,播放声音目录下的声音文件
     * 
     * @param name
     *            声音文件的名字(带后缀)
     */
    public static void playSound(String name) {
    String path = "";
    try {
    //路径问题  项目下 有个sound文件夹  
    URL url = ChessUtil.class.getResource("");
    if (url != null) {
    path = url.getPath() + "sound/" + name;
    InputStream is = new FileInputStream(path);
    AudioStream as = new AudioStream(is);
    AudioPlayer.player.start(as);
    } else {
    System.out.println("声音文件路径获取失败");
    } } catch (IOException ie) {
    ie.printStackTrace();
    }
    }/**
     * @param args
     */
    public static void main(String[] args) {
    ChessUtil.playSound("back.mid");//.mid mp3格式的可以
    }
      

  3.   

    下面的程序是播放当前目录的"3.wav"文件,读取和播放都是用流的相关语句实现,并且可以设置音量
    import java.io.*;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.FloatControl;public class PlayMusic {
        static volatile boolean stop=false;
        public static void main(String[] args) {
            PlayMusic.Play("3.wav");
        }    //播放音频文件
        public static void Play(String fileurl) {        try {
                AudioInputStream ais = AudioSystem.getAudioInputStream(new File(fileurl));
                AudioFormat aif = ais.getFormat();System.out.println(aif);
                final SourceDataLine sdl;
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
                sdl = (SourceDataLine) AudioSystem.getLine(info);
                sdl.open(aif);
                sdl.start();
                FloatControl fc=(FloatControl)sdl.getControl(FloatControl.Type.MASTER_GAIN);
                //value可以用来设置音量,从0-2.0
                double value=2;
                float dB = (float)
                      (Math.log(value==0.0?0.0001:value)/Math.log(10.0)*20.0);
                fc.setValue(dB);
                int nByte = 0;
                int writeByte = 0;
                final int SIZE=1024*64;
                byte[] buffer = new byte[SIZE];
                while (nByte != -1) {
                    nByte = ais.read(buffer, 0, SIZE);
                    sdl.write(buffer, 0, nByte);
                }
                sdl.stop();        } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }