Search code examples
javaresourceswavembedded-resourcejavasound

Java Exception Reading Stream from Resource .wav


I guess my code is okay, and my .jar file its okay with the .wav inside it.. But when I try to load it using getResourceAsStream I get a error..

this is my error:

java.io.IOException: mark/reset not supported
    at java.util.zip.InflaterInputStream.reset(Unknown Source)
    at java.io.FilterInputStream.reset(Unknown Source)
    at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unkno
wn Source)
    at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
    at operation.MainWindowOperations.prepareAudio(MainWindowOperations.java
:92)
    at operation.MainWindowOperations.<init>(MainWindowOperations.java:81)
    at graphics.LaunchGraphics.<init>(LaunchGraphics.java:25)
    at run.RunApp.main(RunApp.java:14)

this is my code:

private void prepareAudio() {
    try {

        InputStream is = this.getClass().getClassLoader().getResourceAsStream("beep.wav");
        inputStream = AudioSystem.getAudioInputStream(is);
        clip = AudioSystem.getClip();
        clip.open(inputStream);

    } catch (Exception ex) {
        ex.printStackTrace();

    }

}

Can someone help me? thanks alot in advance!!


Solution

  • Java Sound requires repositionable (mark/reset supported) input streams for some operations. If you strike this problem it is because the stream is not repositionable.

    One way to get around it is to put the byte[] of the original stream into a ByteArrayInputStream, which supports mark/reset.


    The 2nd answer on the question linked by Eric R. is also a possibility, and looks simpler. To try it, change..

    InputStream is = this.getClass().getClassLoader().getResourceAsStream("beep.wav");
    inputStream = AudioSystem.getAudioInputStream(is);
    

    To:

    URL url = this.getClass().getClassLoader().getResource("beep.wav");
    inputStream = AudioSystem.getAudioInputStream(url);