I want to convert a byte array into an AudioInputStream. The byte array was filled from a *.wav file before. I have the following code:
public static AudioInputStream writeBytesBackToStream(byte[] bytes) {
ByteArrayInputStream baiut = new ByteArrayInputStream(bytes);
AudioInputStream stream = null;
try {
stream = AudioSystem.getAudioInputStream(baiut);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(stream.equals(null) || stream == null) {
System.out.println("WARNING: Stream read by byte array is null!");
}
return stream;
}
Now I only want to convert this byte array into an AudioInputStream, but an UnsupportedAudioFileException is thrown:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
Has anyone got an idea?
If you properly read the WAV file, the byte array will just contain raw PCM data. Consequently the AudioSystem can not identify the format of the stream and throws the exception.
This can not work by design. You need to provide a complete audio format image in your stream to have AudioSystem recognize what format the stream is, not just raw data.
Another way to do this, if the data is actually PCM, is to set the AudioFormat parameters manually. Here is an example to create an A minor.
Also be careful if you're making bytes into sounds and you have earphones in.