import java.io.IOException; import java.io.InputStream; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.sound.sampled.*; public class SoundPlayer implements Runnable { private static final int BUFFER_SIZE = 4096; private static final ExecutorService SOUND_EXECUTOR = Executors.newFixedThreadPool(4, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread t = new Thread(runnable, "SoundEffectPlayer"); t.setDaemon(true); return t; } }); private final InputStream soundStream; private final int delay; private final int soundLevel; public static volatile int volume; /** * Initializes and schedules the sound player. * @param stream * @param level * @param delay */ public SoundPlayer(InputStream stream, int level, int delay) { if (stream == null || level <= 0 || volume >= 4 || level - volume <= 0) { if (stream != null) { try { stream.close(); } catch (IOException ignored) { } } this.soundStream = null; this.soundLevel = 0; this.delay = 0; return; } this.soundStream = stream; this.soundLevel = level; this.delay = delay; SOUND_EXECUTOR.execute(this); } /** * Plays the sound. */ @Override public void run() { if (soundStream == null) { return; } try (AudioInputStream stream = AudioSystem.getAudioInputStream(soundStream)) { AudioFormat format = stream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); try (SourceDataLine sound = (SourceDataLine) AudioSystem.getLine(info)) { sound.open(format); if (sound.isControlSupported(FloatControl.Type.MASTER_GAIN)) { FloatControl gainControl = (FloatControl) sound.getControl(FloatControl.Type.MASTER_GAIN); float db = getDecibels(soundLevel - getVolume()); db = Math.max(gainControl.getMinimum(), Math.min(gainControl.getMaximum(), db)); gainControl.setValue(db); } if (delay > 0) { Thread.sleep(delay); } sound.start(); byte[] buffer = new byte[BUFFER_SIZE]; int nBytesRead; while ((nBytesRead = stream.read(buffer, 0, buffer.length)) != -1) { if (nBytesRead > 0) { sound.write(buffer, 0, nBytesRead); } } sound.drain(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { e.printStackTrace(); } } /** * Sets the client's volume level. * @param level */ public static void setVolume(int level) { volume = level; } /** * Returns the client's volume level. */ public static int getVolume() { return volume; } /** * Returns the decibels for a given volume level. * @param level * @return */ public float getDecibels(int level) { if (level <= 0) { return -1.0f; } switch (level) { case 1: // 3 in player options return -5.0f; case 2: // 2 return -10.0f; case 3: // 1 return -15.0f; default: // 4+ (muted/off) return -100.0f; } } }