I have written a method in java to play a sound. It works fine on my ubuntu laptop but doesnt work on windows. There is no error but i think it might be bypassing the drain method on windows for some reason.
public static void runOnce(final String location) {
new Thread(new Runnable() {
public void run() {
try {
File audioFile = new File(Game.gameFolder + "/sounds/" + location);
final AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
final Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.open(audioStream);
audioClip.start();
audioClip.drain();
try {
audioClip.close();
audioStream.close();
} catch (Exception e) {
System.out.println("heyeyeyeyye");
}
System.out.println("sound method ran");
} catch(Exception e) {}
}
}).start();
}
thanks -Tyler
EDIT: i remember actually it worked on windows before i used drain but after a certain amount of time it wouldnt load anymore so i switched to drain
I suggest you use try-with-resources
and that you join()
the Thread you start and never swallow the message from your Exception
. Something like,
public static void runOnce(final String location) {
File audioFile = new File(Game.gameFolder + "/sounds/" + location);
Thread t = new Thread(new Runnable() {
public void run() {
try (AudioInputStream audioStream = AudioSystem
.getAudioInputStream(audioFile);) {
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
try (Clip audioClip = (Clip) AudioSystem.getLine(info);) {
audioClip.open(audioStream);
audioClip.start();
audioClip.drain();
}
System.out.println("heyeyeyeyye");
System.out.println("sound method ran");
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
t.join();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.