Search code examples
javaaudiowavjavasoundclip

Invalid format with getAudioInputStream, trying to play a sound in Java


I'm trying to just play a basic sound in Java...

Here is my code, based on the code found on various forums :

    Clip clip = null;

    try {
        clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(url));
        clip.open(inputStream);
    } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) {
        Logger.getLogger(Pomodoro.class.getName()).log(Level.SEVERE, null, ex);
    }

    return clip;

I checked that : new File(url).exists(); returns true, I checked that the file type is really audio WAV (audio/x-wav), I checked that the problem persists with another file... I don't understand what I'm doing wrong.

The error :

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: 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)

Help !


Solution

  • I finally found a duplicate of my issue. Sorry I bothered you.

    AudioInputStream is not working

    My code became :

        Clip clip = null;
    
        try {
            AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(url));
            DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat());
            clip = (Clip)AudioSystem.getLine(info);
            clip.open(inputStream);
        } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) {
            Logger.getLogger(Pomodoro.class.getName()).log(Level.SEVERE, null, ex);
        }
    
        return clip;
    

    Nevertheless, I'm very surprised that my previous code didn't work. Sometimes, I'm quite desperate by Java...