How to preload AudioClip in Java
I am using this class to play a song in my program:
public class Sound extends Thread {
private static AudioClip song;
public Sound(String songUrl) {
try{
URL songFile = SoundRessources.class.getResource(songUrl);
song = Applet.newAudioClip(songFile);
}catch(NullPointerException e){
System.out.println("impossible de trouver la musique");
}
}
public void playSound() {
song.play();
}
}
But when I play like this:
new Sound("xxxxx/xxxx.wav").play();
A few seconds before the sound starts playing.
My question is: Can I preload sound? Maybe the library is more responsive than this applet? Or do you have an idea to play instantly?
+3
source to share
1 answer
Your use is Thread
very strange. If you want to load a clip on a background thread and then start playing, you will need to change:
public class BackroundSound extends Thread {
private String songUrl;
public BackroundSound(String url) {
songUrl = url;
}
//load in background and then start playing
@Override
public void run() {
if (songUrl == null) {
// log error, url wasn't set
}
URL songFile = SoundRessources.class.getResource(songUrl);
AudioClip song = Applet.newAudioClip(songFile);
song.play();
// log - playback is finished
}
}
Loading and playing sound:
new BackroundSound("xxxxx/xxxx.wav").start();
+1
source to share