[英]How to play a WAV in Java, when the WAV is contained inside the JAR
I've been trying to deal with sound on my Applet for a bit now, and Instead of trying all the different methods, what is the best way to play Sound in Java? 我一直在尝试处理Applet上的声音,而不是尝试所有不同的方法,而用Java播放声音的最佳方法是什么? There are a few requirements:
有一些要求:
Thanks you so much for looking at my question and I hope you guys have an answer! 非常感谢您查看我的问题,希望大家有答案!
Thanks to the wonderful help I almost have it working with this: 由于有了出色的帮助,我几乎可以使用它:
public class MyGame() {
Clip bullet;
public void init(){
try {
bullet = AudioSystem.getClip();
URL url2 = this.getClass().getResource("bulletSound.wav");
AudioInputStream ais2 = AudioSystem.getAudioInputStream( url2 );
bullet.open(ais2);
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
randomMethodToPlayBullet(){
bullet.setFramePosition(0);
bullet.start();
}
}
The problem is that the bullet sound plays, but if the randomMethodToPlayBullet is called say twice in a row, before the first bullet sound is done, the seonc one doesnt play. 问题是子弹声音会播放,但是如果在第一个子弹声音完成之前连续两次调用randomMethodToPlayBullet,则第二个子弹不会播放。
The best way to load resources from jar file is to put in the same folder a class and get the resource with .class.getResource(...)
or .class.getResourceaAsStream(...)
methods: 从jar文件加载资源的最佳方法是将一个类放在同一文件夹中,并使用
.class.getResource(...)
或.class.getResourceaAsStream(...)
方法获取资源:
URL url = ClazzInTheFolderOfMyMidiFile.class.getResource(nameOfMidiFile);
or 要么
InputStream resourceAsStream = ClazzInTheFolderOfMyMidiFile.class.getResourceAsStream(nameOfMidiFile);
You can't play the same Clip twice at the same time. 您不能同时播放同一剪辑两次。 You have to create another instance of Clip to play the sound twice at the same time.
您必须创建另一个Clip实例才能同时播放两次声音。
Note that there will be a limit how many clips you can play, so the clip API may not be suited to support a sound-heavy game. 请注意,可以播放的剪辑数量是有限制的,因此剪辑API可能不适合支持声音大的游戏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.