java audiosystem_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 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值