我想播放一个wav文件,在我用Google搜索后,我找到了这个脚本,但它不起作用。 (它没有抛出任何异常,也没有编译问题)
import java.io.File;
import films.Film;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class MusicStorage {
/**
* Opens a wav file and plays it
* @param args
*/
public void play(Film song) {
try {
Clip sound = AudioSystem.getClip();
sound.open(AudioSystem.getAudioInputStream(new File(song.getClip())));
sound.start();
while (sound.isRunning())
Thread.sleep(1000);
sound.close();
} catch (Exception e) {
System.out.println("Whatever" + e);
}
}
}
import audio.MusicStorage;
import films.Film;
public class Aplication {
private static Film gladiator = new Film("Gladiator", "gladiator.wav");
private static MusicStorage storage = new MusicStorage();
public static void main(String[] args) {
storage.play(gladiator);
}
}
public class Film {
private String name;
private String clip;
public Film(String name, String clip) {
this.name = name;
this.clip = clip;
}
public String getClip() {
return clip;
}
public String getName() {
return name;
}
}
我添加了所有代码,所以希望能解决我的问题
答案 0 :(得分:0)
只需从代码中删除while循环即可修复。 while循环使线程休眠,因此无法播放音频文件。
public void play(Film song) {
try {
Clip sound = AudioSystem.getClip();
sound.open(AudioSystem.getAudioInputStream(new File(song.getClip())));
sound.start();
} catch (Exception e) {
System.out.println("Whatever" + e);
}
}
}