如何播放音频文件?

时间:2015-01-12 13:36:17

标签: java audio javasound

我无法在蛇和梯子游戏中播放音频文件。它应该在玩家摔倒蛇时播放。

import sun.audio.AudioData;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;


public void playFallingSound()
    {
        AudioPlayer MGP = AudioPlayer.player;
        AudioStream BGM;
        AudioData MD;
        ContinuousAudioDataStream loop = null;

        try{
        BGM = new AudioStream (new FileInputStream("PacMan.wav"));
        MD = BGM.getData();
        loop= new ContinuousAudioDataStream (MD);
        } catch (IOException error) {System.out.println("Error playing falling sound");}
        MGP.start(loop);
    }

1 个答案:

答案 0 :(得分:0)

尝试此功能:

public static synchronized void playSound(final String url) {
                new Thread(new Runnable() {
                  public void run() {
                    try {
                      Clip clip = AudioSystem.getClip();
                      AudioInputStream inputStream = AudioSystem.getAudioInputStream(ChatClient.class.getResourceAsStream("/resources/" + url));
                      clip.open(inputStream);
                      clip.start();
                    } catch (Exception e) {
                      System.err.println(e.getMessage());
                    }
                  }
                }).start();
              }