How to preload differents clips with AudioSystem?

问题: I'm integrated audio in a Java application. The problem is that sometimes clip.open() hangs up a little so I've read that I need to reload the clip and then just clip.start...

问题:

I'm integrated audio in a Java application. The problem is that sometimes clip.open() hangs up a little so I've read that I need to reload the clip and then just clip.start().

I'm using a sound class for each audio file, it reloads the clip once it has finish playing. The problem here is that the sound I trigger doesn't play right when I trigger it, but when I trigger the next sound. It shifts all sounds.

I've came up with the idea that it happens becouse the load method opens a clip that is then used by a different Sound instance, ¿Shoudn´t it just load it's clip?

Like I said, if a call the load method right after start, it freezes sometimes. I've created a thread to run it, so that it doesn't hang the main thread, but it freezes anyway so the sound plays late.

public class Sound {

    private final String file;
    private static Clip clip;

    public Sound(String file){
        this.file = file;
        load();
    }

    public final void load(){
        try {
            AudioInputStream stream = AudioSystem.getAudioInputStream(new File(file).getAbsoluteFile());
            clip = AudioSystem.getClip();
            System.out.println(clip);
            clip.open(stream);
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException  ex) {
            Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void play() {
        clip.start();
        clip.addLineListener(e -> {
            if (e.getType() == LineEvent.Type.STOP) {
                clip.stop();
                clip.close();
                load();
            }
        });
    }

}

I expect the audio to played at the moment when it's triggered.


回答1:

I figured it out. It was such a stupid mistake. Clip was the same to all clases, not becouse getClip() returned the same value, but becouse I set it to be static. Just changed:

private static Clip clip;

to

private Clip clip;
  • 发表于 2019-03-27 00:29
  • 阅读 ( 345 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除