[英]Playing wav file in java
Im trying to make sound effects for my game but i couldn't achieve to play it yet. 我正在尝试为我的游戏制作音效,但我还无法实现播放效果。 I have looked up everywhere but everytime that i try to do what i see i always have this error:
我到处都抬头,但是每次尝试做我看到的东西时,我总是会遇到此错误:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at pong.Pong.loadResources(Pong.java:114)
at pong.Pong.<init>(Pong.java:69)
at pong.Pong.main(Pong.java:34)
This the code that i try to run: 这是我尝试运行的代码:
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("score.wav"));
AudioFormat format = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(audioInputStream);
clip.start();
} catch (UnsupportedAudioFileException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Just to be sure, i placed the same named same wav file under directly the project folder, src folder, res folder too. 可以肯定的是,我也直接在项目文件夹,src文件夹,res文件夹下放置了相同名称的相同wav文件。 I would like to have it opened from res folder by the way but first thing i have to do is just fixing the code to play the sound.
我想顺便从res文件夹中打开它,但我要做的第一件事就是修复代码以播放声音。 Then i can work with the path declaration.
然后,我可以使用路径声明。 Any help would be appreciated!
任何帮助,将不胜感激!
Try something like this: 尝试这样的事情:
File file = new File("clip.wav");
if(file.exists()) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[128000];
while (nBytesRead != -1) {
try {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
} catch (UnsupportedAudioFileException | IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
} else {
System.err.println("The selected file doesn't exist!");
}
It works fine. 工作正常。 If you are using Eclipse (I don't know how it works with others IDEs) make sure you place the file in the project's root folder.
如果您使用的是Eclipse(我不知道它如何与其他IDE一起使用),请确保将文件放在项目的根文件夹中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.