import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; public class SoundPlayer { private static SoundPlayer instance; private Clip mClip; public static SoundPlayer get() { if (instance == null) instance = new SoundPlayer(); return instance; } private SoundPlayer() { final File soundFile = new File("./res/my_sound.wav"); try { mClip = AudioSystem.getClip(); mClip.open(AudioSystem.getAudioInputStream(soundFile)); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { throw new RuntimeException(e); } } public void playMySound() { if (mClip != null) { mClip.setMicrosecondPosition(0); // Reset to the start of the file mClip.start(); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter