我已经尝试过几十个教程,但我还没有能够让他们中的任何一个工作。我只想在我的应用程序的后台播放.wav文件。
答案 0 :(得分:1)
请参阅:How to Play .wav File with JButton?
public void playSound(String soundName)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}
答案 1 :(得分:0)
请试试以下内容吗?
public class PlayAudio {
private AudioInputStream inputStream;
private AudioFormat format;
private SourceDataLine sourceDataLine;
private File file;
private final int BUFFER_SIZE = 128000;
public void playSound(String filename) throws Exception {
String strFilename = filename;
file = new File(strFilename);
inputStream = AudioSystem.getAudioInputStream(file);
format = inputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
sourceDataLine.open(format);
sourceDataLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = inputStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
@SuppressWarnings("unused")
int nBytesWritten = sourceDataLine.write(abData, 0, nBytesRead);
}
}
sourceDataLine.drain();
sourceDataLine.close();
}
}