我正在用Java播放.wav声音。我有一些看起来像这样的代码:
package tools;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
public class ClipHandler implements LineListener {
private Clip clip;
public ClipHandler(Clip clip) {
this.clip = clip;
clip.addLineListener(this);
}
public void play() {
clip.start();
}
public void update(LineEvent e) {
if (e.getType() == LineEvent.Type.STOP) {
clip.close();
}
}
}
被调用的方法:
public static void play(String path) {
try {
URL soundUrl = SoundTools.class.getResource(path);
AudioInputStream stream = AudioSystem.getAudioInputStream(soundUrl);
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
new ClipHandler(clip).play();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
当我尝试播放.wav文件时会出现问题。它总是第一次工作,但经过几次调用游戏(路径)后,我正在玩游戏的窗口完全冻结;它不会让我做任何事情。我需要帮助!顺便说一下,我调用这样的代码:SoundTools.play(soundPath);
答案 0 :(得分:0)
clip.close()
中运行Thread
。为什么?我认为这与需要时间关闭这一事实有关,但是我的事情正在冻结。呃,它有效!这是:
package tools;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
public class ClipHandler implements LineListener, Runnable {
private Clip clip;
public ClipHandler(Clip clip) {
this.clip = clip;
clip.addLineListener(this);
}
public void play() {
clip.start();
}
public void update(LineEvent e) {
if (e.getType() == LineEvent.Type.STOP) {
System.out.println("stopping!");
new Thread(this).start();
}
}
public void run() {
clip.close();
System.out.println("stopped!");
}
}
方法(在同一个包中(如果它不是,导入SoundTools)):
public static synchronized void play(String path) {
try {
URL soundUrl = SoundTools.class.getResource(path);
AudioInputStream stream = AudioSystem.getAudioInputStream(soundUrl);
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
new ClipHandler(clip).play();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
我希望你们都觉得这很有用! 附:这适用于.jars!