-2
我已經嘗試了幾十個教程,但我一直無法讓他們工作。我只想要一個.wav文件在我的應用程序的背景中播放。如何在Java中播放.wav文件?
我已經嘗試了幾十個教程,但我一直無法讓他們工作。我只想要一個.wav文件在我的應用程序的背景中播放。如何在Java中播放.wav文件?
參見: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();
}
}
可否請您嘗試以下?
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();
}
}
如果你已經嘗試過「幾十個東西」,想必你能告訴我們究竟那些「數十名」是如此,我們不只是一次又一次的告訴你同樣的事情。 – Dragondraikk