剪辑有时不播放 [英] Clip sometimes does not play
问题描述
我有一个Sound类,其中包含一个方法,在调用时,使用Clip对象播放声音(在这种情况下, clip
)。
I have a Sound class that contains a method that, when called, plays a sound using a Clip object (in this case, clip
).
public static void play() {
clip.stop(); // The purpose of the first three lines
clip.flush(); // is to restart the Clip object so it
clip.setFramePosition(0); // can be played multiple times.
clip.start();
}
Clip对象的实例化发生在一个单独的静态方法中,该方法称为先验这个方法,这就是上述方法可以声明为静态的原因。
The instantiation of the Clip object occurs in a separate static method which is called prior to this method, which is why the above method can be declared static.
另一个实现 KeyListener
的类包含以下代码:
Another class that implements KeyListener
contains the following code:
public void keyPressed(KeyEvent e) {
Sound.play(); // Sound is the class that implements the previous method.
}
因此,我的代码应播放与剪辑
。但是,如果我快速反复按键,声音有时会无法播放。一段时间后这一点尤为明显(每次按键后问题似乎都会变得更糟)。
Therefore, my code should be playing the sound associated with clip
everytime a key is pressed. However, if I press a key quickly and repeatedly, the sound will sometimes not play. This is especially noticeable after a while (It seems as though the problem gets worse after each key press).
为什么会发生这种情况,我该如何规避这个问题呢?
Why does this happen, and how can I circumvent this problem?
推荐答案
过去我遇到过同样的问题,对我来说有用的是每次都添加一个线条监听器一条线已经完成并关闭它。
I have had the same kind of problems in the past, and something which worked for me is adding a line listener for whenever a line has finished, and closing it.
下面的代码是我使用的精简版:
The code underneath is a stripped down version of what I use:
music = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(Sound.class.getResource("/sounds" + filename));
music.open(ais);
music.addLineListener(new LineListener(){
public void update(LineEvent e){
if(e.getType() == LineEvent.Type.STOP){
e.getLine().close();
}
}
});
music.start();
创建剪辑时,只需添加行侦听器即可。使用播放功能重置剪辑时,它应该正常播放。我希望这适合你!
When you create the clip, just add in the line listener. When you reset the clip using your play function, it should play properly. I hope this works for you!
这篇关于剪辑有时不播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!