javaaudiojavasoundjavax.sound.sampled

AudioInputStream is not working


I'm trying to play a .wav sound every time the user presses a button, but an exception gets thrown:

Exception in thread "Thread-0" java.lang.IllegalArgumentException: Invalid format
    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.createStream(PulseAudioDataLine.java:142)
    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:99)
    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:283)
    at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:402)
    at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:453)
    at Uber.play(Uber.java:534)
    at Uber$5.run(Uber.java:340)
    at java.lang.Thread.run(Thread.java:724)

Here's the code:

//Play Audio File
public void play(String file) throws LineUnavailableException, UnsupportedAudioFileException, IOException
{
    AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(file));
    Clip clip = AudioSystem.getClip();
    clip.open(inputStream);
    clip.start();
}

Solution

  • I managed to get it working. This is the code that I used. Keep in mind that I needed this just to play a short beep.wav sound. It seems to have some trouble with longer sound files. Let me know if it works for you guys and if you manage to play longer sounds with this code.

    public void play(String file) throws LineUnavailableException, UnsupportedAudioFileException, IOException
        {
    
        try 
            {   
                AudioInputStream inputStream = AudioSystem.getAudioInputStream(this.getClass().getResource(file));
                AudioFormat format = inputStream.getFormat();
                DataLine.Info info = new DataLine.Info(Clip.class, format);
                Clip clip = (Clip)AudioSystem.getLine(info);
                clip.open(inputStream);
                clip.start();
            }
    
        catch (IOException | LineUnavailableException | UnsupportedAudioFileException e1)
            {
                e1.printStackTrace();
            }
        }