class SoundPlayer
{
private static final BlockingQueue<String> soundQueue = new LinkedBlockingQueue<>();
private static final ExecutorService soundExecutor = Executors.newSingleThreadExecutor();
private static volatile boolean isRunning = true;
private static volatile Clip currentClip = null;
static {
soundExecutor.execute(() -> {
while (isRunning) {
try {
String soundFile = soundQueue.take(); // blocks until a sound is available
playSoundInternal(soundFile);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
}
public static void playSound(String soundDir, String filePath)
{
if (soundDir.contains("\\")) { soundDir = soundDir.replace("\\", "/"); }
filePath = soundDir + "/" + filePath;
System.out.println("Queueing sound: " + filePath);
soundQueue.add(filePath);
}
private static void playSoundInternal(String filePath)
{
try (AudioInputStream audioStream = AudioSystem.getAudioInputStream(new File(filePath))) {
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
currentClip = clip;
// Add listener to handle when playback finishes
clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) {
clip.close();
currentClip = null;
processNextSound();
}
});
clip.start(); // play sound
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
System.out.println("Error playing sound: " + e.getMessage());
processNextSound();
}
}
private static void processNextSound()
{
if (!soundQueue.isEmpty()) {
soundExecutor.execute(() -> {
try {
String nextSound = soundQueue.take();
playSoundInternal(nextSound);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}
public static void shutdown()
{
isRunning = false;
soundExecutor.shutdownNow();
if (currentClip != null && currentClip.isRunning()) {
currentClip.stop();
currentClip.close();
}
}
}
SoundPlayer.playSound(soundDir, "kaching.wav");