user1527723
user1527723

Reputation: 33

Java UnsupportedAudioFileException when using FileInputStream

I an having a problem when trying to play sounds with Java; if I use

AudioInputStream soundIn = AudioSystem.getAudioInputStream(new File("./sound.wav"));

to get the AudioInputStream, it works and the file plays correctly. However, if I use

AudioInputStream soundIn = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream("./sound.wav")));

I get

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream

What I am trying to do is play back audio that I have recorded from the microphone, and I have it saved as a WAV file in a byte array in memory, and I cannot get it to play. However, if I save it to a file and use the File object directly, it plays. But if I use any kind of InputStream, it fails with that exception, including when I use this code:

AudioInputStream soundIn = AudioSystem.getAudioInputStream(new BufferedInputStream(new ByteArrayInputStream(recorder.getLastRecording())));

Where recorder.getLastRecording() returns a byte array. Any ideas?

Upvotes: 2

Views: 2516

Answers (2)

Phil Freihofner
Phil Freihofner

Reputation: 7910

This error has actually come up numerous times in various guises.

What I think is going on is that whenever you try to use an InputStream, or use code that requires an InputStream as one of the intermediate steps, Java tests whether the file is valid as an InputStream: does it support "marking" is one such test, also whether the file is "resettable".

Note that your error message says that it is unable to get a valid file from the InputStream. This is probably because Java is unable to perform one or the other commands on the file, and thus won't consider it a valid InputStream.

If you open a file from a File location or better, a URL (imho), then AudioSystem.getAudioInputStream does not go through the intermediate step of testing if the file can function as a valid InputStream.

Actually, the following javadef supports what I am saying pretty clearly.

http://docs.oracle.com/javase/6/docs/api/javax/sound/sampled/AudioSystem.html#getAudioInputStream(java.io.InputStream)

Note that if you compare the various forms of "getAudioInputStream", you will see how there are extra requirements concerning the file in the InputStream parameter version compared to the URL and File parameter versions.

I like using a URL the best, as URLs work well with locating files in jars, and resources can be specified in relationship to the root directory of the code or class.

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168845

// lose the BufferedInputStream
AudioInputStream soundIn = AudioSystem.getAudioInputStream(
    new ByteArrayInputStream(recorder.getLastRecording()));

Upvotes: 1

Related Questions