<p>I want to be able to play sound files in my program. Where should I look?</p>

[{'answer_id': 26311, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 4, 'selected': False, 'text': '<p>A bad example:</p>\n\n<pre><code>import  sun.audio.*;    //import the sun.audio package\nimport  java.io.*;\n\n//** add this into your application code as appropriate\n// Open an input stream  to the audio file.\nInputStream in = new FileInputStream(Filename);\n\n// Create an AudioStream object from the input stream.\nAudioStream as = new AudioStream(in);         \n\n// Use the static class member "player" from class AudioPlayer to play\n// clip.\nAudioPlayer.player.start(as);            \n\n// Similarly, to stop the audio.\nAudioPlayer.player.stop(as); \n</code></pre>\n'}, {'answer_id': 26318, 'author': 'pek', 'author_id': 2644, 'author_profile': 'https://Stackoverflow.com/users/2644', 'pm_score': 8, 'selected': True, 'text': '<p>I wrote the following code that works fine. But I think it only works with <code>.wav</code> format.</p>\n\n<pre><code>public static synchronized void playSound(final String url) {\n  new Thread(new Runnable() {\n  // The wrapper thread is unnecessary, unless it blocks on the\n  // Clip finishing; see comments.\n    public void run() {\n      try {\n        Clip clip = AudioSystem.getClip();\n        AudioInputStream inputStream = AudioSystem.getAudioInputStream(\n          Main.class.getResourceAsStream("/path/to/sounds/" + url));\n        clip.open(inputStream);\n        clip.start(); \n      } catch (Exception e) {\n        System.err.println(e.getMessage());\n      }\n    }\n  }).start();\n}\n</code></pre>\n'}, {'answer_id': 2084262, 'author': 'Stephen Ware', 'author_id': 252964, 'author_profile': 'https://Stackoverflow.com/users/252964', 'pm_score': 2, 'selected': False, 'text': '<p>There is an alternative to importing the sound files which works in both applets and applications: convert the audio files into .java files and simply use them in your code.</p>\n\n<p>I have developed a tool which makes this process a lot easier.  It simplifies the Java Sound API quite a bit.</p>\n\n<p><a href="http://stephengware.com/projects/soundtoclass/" rel="nofollow noreferrer">http://stephengware.com/projects/soundtoclass/</a></p>\n'}, {'answer_id': 15694770, 'author': 'hamilton.lima', 'author_id': 1953431, 'author_profile': 'https://Stackoverflow.com/users/1953431', 'pm_score': 2, 'selected': False, 'text': '<p>I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.</p>\n\n<p><a href="https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java" rel="nofollow">https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java</a></p>\n\n<p>Here is the code for reference.</p>\n\n<pre><code>package com.athanazio.jaga.desktop.sound;\n\nimport java.io.BufferedInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.AudioInputStream;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.DataLine;\nimport javax.sound.sampled.LineUnavailableException;\nimport javax.sound.sampled.SourceDataLine;\nimport javax.sound.sampled.UnsupportedAudioFileException;\n\npublic class Sound {\n\n    AudioInputStream in;\n\n    AudioFormat decodedFormat;\n\n    AudioInputStream din;\n\n    AudioFormat baseFormat;\n\n    SourceDataLine line;\n\n    private boolean loop;\n\n    private BufferedInputStream stream;\n\n    // private ByteArrayInputStream stream;\n\n    /**\n     * recreate the stream\n     * \n     */\n    public void reset() {\n        try {\n            stream.reset();\n            in = AudioSystem.getAudioInputStream(stream);\n            din = AudioSystem.getAudioInputStream(decodedFormat, in);\n            line = getLine(decodedFormat);\n\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    public void close() {\n        try {\n            line.close();\n            din.close();\n            in.close();\n        } catch (IOException e) {\n        }\n    }\n\n    Sound(String filename, boolean loop) {\n        this(filename);\n        this.loop = loop;\n    }\n\n    Sound(String filename) {\n        this.loop = false;\n        try {\n            InputStream raw = Object.class.getResourceAsStream(filename);\n            stream = new BufferedInputStream(raw);\n\n            // ByteArrayOutputStream out = new ByteArrayOutputStream();\n            // byte[] buffer = new byte[1024];\n            // int read = raw.read(buffer);\n            // while( read &gt; 0 ) {\n            // out.write(buffer, 0, read);\n            // read = raw.read(buffer);\n            // }\n            // stream = new ByteArrayInputStream(out.toByteArray());\n\n            in = AudioSystem.getAudioInputStream(stream);\n            din = null;\n\n            if (in != null) {\n                baseFormat = in.getFormat();\n\n                decodedFormat = new AudioFormat(\n                        AudioFormat.Encoding.PCM_SIGNED, baseFormat\n                                .getSampleRate(), 16, baseFormat.getChannels(),\n                        baseFormat.getChannels() * 2, baseFormat\n                                .getSampleRate(), false);\n\n                din = AudioSystem.getAudioInputStream(decodedFormat, in);\n                line = getLine(decodedFormat);\n            }\n        } catch (UnsupportedAudioFileException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        } catch (LineUnavailableException e) {\n            e.printStackTrace();\n        }\n    }\n\n    private SourceDataLine getLine(AudioFormat audioFormat)\n            throws LineUnavailableException {\n        SourceDataLine res = null;\n        DataLine.Info info = new DataLine.Info(SourceDataLine.class,\n                audioFormat);\n        res = (SourceDataLine) AudioSystem.getLine(info);\n        res.open(audioFormat);\n        return res;\n    }\n\n    public void play() {\n\n        try {\n            boolean firstTime = true;\n            while (firstTime || loop) {\n\n                firstTime = false;\n                byte[] data = new byte[4096];\n\n                if (line != null) {\n\n                    line.start();\n                    int nBytesRead = 0;\n\n                    while (nBytesRead != -1) {\n                        nBytesRead = din.read(data, 0, data.length);\n                        if (nBytesRead != -1)\n                            line.write(data, 0, nBytesRead);\n                    }\n\n                    line.drain();\n                    line.stop();\n                    line.close();\n\n                    reset();\n                }\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 20514020, 'author': 'Ishwor', 'author_id': 2118080, 'author_profile': 'https://Stackoverflow.com/users/2118080', 'pm_score': 3, 'selected': False, 'text': '<p>For playing sound in java, you can refer to the following code.</p>\n\n<pre><code>import java.io.*;\nimport java.net.URL;\nimport javax.sound.sampled.*;\nimport javax.swing.*;\n\n// To play sound using Clip, the process need to be alive.\n// Hence, we use a Swing application.\npublic class SoundClipTest extends JFrame {\n\n   public SoundClipTest() {\n      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n      this.setTitle("Test Sound Clip");\n      this.setSize(300, 200);\n      this.setVisible(true);\n\n      try {\n         // Open an audio input stream.\n         URL url = this.getClass().getClassLoader().getResource("gameover.wav");\n         AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);\n         // Get a sound clip resource.\n         Clip clip = AudioSystem.getClip();\n         // Open audio clip and load samples from the audio input stream.\n         clip.open(audioIn);\n         clip.start();\n      } catch (UnsupportedAudioFileException e) {\n         e.printStackTrace();\n      } catch (IOException e) {\n         e.printStackTrace();\n      } catch (LineUnavailableException e) {\n         e.printStackTrace();\n      }\n   }\n\n   public static void main(String[] args) {\n      new SoundClipTest();\n   }\n}\n</code></pre>\n'}, {'answer_id': 35162134, 'author': 'Cyril Duchon-Doris', 'author_id': 2832282, 'author_profile': 'https://Stackoverflow.com/users/2832282', 'pm_score': 4, 'selected': False, 'text': '<p>I didn\'t want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).</p>\n\n<pre><code>private static void playSound(String sound){\n    // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();\n    URL file = cl.getResource(sound);\n    final Media media = new Media(file.toString());\n    final MediaPlayer mediaPlayer = new MediaPlayer(media);\n    mediaPlayer.play();\n}\n</code></pre>\n\n<p>Notice : You need to <a href="https://stackoverflow.com/questions/14025718/javafx-toolkit-not-initialized-when-trying-to-play-an-mp3-file-through-mediap">initialize JavaFX</a>. A quick way to do that, is to call the constructor of JFXPanel() once in your app :</p>\n\n<pre><code>static{\n    JFXPanel fxPanel = new JFXPanel();\n}\n</code></pre>\n'}, {'answer_id': 37693420, 'author': 'Andrew Jenkins', 'author_id': 2657020, 'author_profile': 'https://Stackoverflow.com/users/2657020', 'pm_score': 3, 'selected': False, 'text': '<p>For whatever reason, the top answer by wchargin was giving me a null pointer error when I was calling this.getClass().getResourceAsStream().</p>\n\n<p>What worked for me was the following:</p>\n\n\n\n<pre class="lang-java prettyprint-override"><code>void playSound(String soundFile) {\n    File f = new File("./" + soundFile);\n    AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());  \n    Clip clip = AudioSystem.getClip();\n    clip.open(audioIn);\n    clip.start();\n}\n</code></pre>\n\n<p>And I would play the sound with:</p>\n\n<pre class="lang-java prettyprint-override"><code> playSound("sounds/effects/sheep1.wav");\n</code></pre>\n\n<p>sounds/effects/sheep1.wav was located in the base directory of my project in Eclipse (so not inside the src folder).</p>\n'}, {'answer_id': 39965540, 'author': 'Galen Nare', 'author_id': 2737479, 'author_profile': 'https://Stackoverflow.com/users/2737479', 'pm_score': 0, 'selected': False, 'text': '<p>This thread is rather old but I have determined an option that could prove useful.</p>\n\n<p>Instead of using the Java <code>AudioStream</code> library you could use an external program like Windows Media Player or VLC and run it with a console command through Java.</p>\n\n<pre><code>String command = "\\"C:/Program Files (x86)/Windows Media Player/wmplayer.exe\\" \\"C:/song.mp3\\"";\ntry {\n    Process p = Runtime.getRuntime().exec(command);\ncatch (IOException e) {\n    e.printStackTrace();\n}\n</code></pre>\n\n<p>This will also create a separate process that can be controlled it the program. </p>\n\n<pre><code>p.destroy();\n</code></pre>\n\n<p>Of course this will take longer to execute than using an internal library but there may be programs that can start up faster and possibly without a GUI given certain console commands. </p>\n\n<p>If time is not of the essence then this is useful.</p>\n'}, {'answer_id': 54341775, 'author': 'Nav', 'author_id': 453673, 'author_profile': 'https://Stackoverflow.com/users/453673', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m surprised nobody suggested using Applet. <a href="https://stackoverflow.com/a/3780445/453673">Use</a> <code>Applet</code>. You\'ll have to supply the beep audio file as a <code>wav</code> file, but it works. I tried this on Ubuntu:  </p>\n\n<pre><code>package javaapplication2;\n\nimport java.applet.Applet;\nimport java.applet.AudioClip;\nimport java.io.File;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic class JavaApplication2 {\n\n    public static void main(String[] args) throws MalformedURLException {\n        File file = new File("/path/to/your/sounds/beep3.wav");\n        URL url = null;\n        if (file.canRead()) {url = file.toURI().toURL();}\n        System.out.println(url);\n        AudioClip clip = Applet.newAudioClip(url);\n        clip.play();\n        System.out.println("should\'ve played by now");\n    }\n}\n//beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav\n</code></pre>\n'}, {'answer_id': 63436083, 'author': 'Arsen Tagaev', 'author_id': 12102080, 'author_profile': 'https://Stackoverflow.com/users/12102080', 'pm_score': 2, 'selected': False, 'text': '<p>It works for me. Simple variant</p>\n<pre><code>public void makeSound(){\n    File lol = new File(&quot;somesound.wav&quot;);\n    \n\n    try{\n        Clip clip = AudioSystem.getClip();\n        clip.open(AudioSystem.getAudioInputStream(lol));\n        clip.start();\n    } catch (Exception e){\n        e.printStackTrace();\n    }\n}\n</code></pre>\n'}, {'answer_id': 67658292, 'author': 'Adir D', 'author_id': 6130501, 'author_profile': 'https://Stackoverflow.com/users/6130501', 'pm_score': 0, 'selected': False, 'text': '<p>I faced many issues to play mp3 file format\nso converted it to .wav using some <a href="https://online-audio-converter.com/" rel="nofollow noreferrer">online converter</a></p>\n<p>and then used below code (it was easier instead of mp3 supporting)</p>\n<pre><code>try\n{\n    Clip clip = AudioSystem.getClip();\n    clip.open(AudioSystem.getAudioInputStream(GuiUtils.class.getResource(&quot;/sounds/success.wav&quot;)));\n    clip.start();\n}\ncatch (Exception e)\n{\n    LogUtils.logError(e);\n}\n</code></pre>\n'}, {'answer_id': 68312041, 'author': 'devp', 'author_id': 8234870, 'author_profile': 'https://Stackoverflow.com/users/8234870', 'pm_score': 1, 'selected': False, 'text': '<pre><code>import java.net.URL;\nimport java.net.MalformedURLException;\nimport javax.sound.sampled.AudioInputStream;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.Clip;\nimport javax.sound.sampled.LineUnavailableException;\nimport javax.sound.sampled.UnsupportedAudioFileException;\nimport java.io.IOException;\nimport java.io.File;\npublic class SoundClipTest{\n    //plays the sound\n    public static void playSound(final String path){\n        try{\n            final File audioFile=new File(path);\n            AudioInputStream audioIn=AudioSystem.getAudioInputStream(audioFile);\n            Clip clip=AudioSystem.getClip();\n            clip.open(audioIn);\n            clip.start();\n            long duration=getDurationInSec(audioIn);\n            //System.out.println(duration);\n            //We need to delay it otherwise function will return\n            //duration is in seconds we are converting it to milliseconds\n            Thread.sleep(duration*1000);\n        }catch(LineUnavailableException | UnsupportedAudioFileException | MalformedURLException | InterruptedException exception){\n            exception.printStackTrace();\n        }\n        catch(IOException ioException){\n            ioException.printStackTrace();\n        }\n    }\n    //Gives duration in seconds for audio files\n    public static long getDurationInSec(final AudioInputStream audioIn){\n        final AudioFormat format=audioIn.getFormat();\n        double frameRate=format.getFrameRate();\n        return (long)(audioIn.getFrameLength()/frameRate);\n    }\n    ////////main//////\n    public static void main(String $[]){\n        //SoundClipTest test=new SoundClipTest();\n        SoundClipTest.playSound(&quot;/home/dev/Downloads/mixkit-sad-game-over-trombone-471.wav&quot;);\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/26305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2644/']