我有从 .wav 文件播放声音的代码,但我无法停止歌曲,甚至无法退出程序直到它结束。因为这是一首 5 分钟的歌曲,所以这是个问题。这是我如何播放 wav 的代码:
public class EasySound{
private SourceDataLine line = null;
private byte[] audioBytes;
private int numBytes;
public EasySound(String fileName){
File soundFile = new File(fileName);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception ex) {
System.out.println("*** Cannot find " + fileName + " ***");
System.exit(1);
}
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try {
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(audioFormat);
} catch (LineUnavailableException ex) {
System.out.println("*** Audio line unavailable ***");
System.exit(1);
}
line.start();
audioBytes = new byte[(int)soundFile.length()];
try {
numBytes = audioInputStream.read(audioBytes, 0, audioBytes.length);
} catch (IOException ex) {
System.out.println("*** Cannot read " + fileName + " ***");
System.exit(1);
}
}
public void play() {
line.write(audioBytes, 0, numBytes);
}
}
有没有更好的方法来做到这一点,或者有一种方法可以让我在播放中停止歌曲?
提前致谢!