0

I'm trying to read a .wav file into an array of bytes to be sent over a socket connection and played on the other side. I'm coming up with a problem once the header data of the file is read, the rest of the file simply fills the byte array with 0. Here's the sample code. I've tried a couple of other approaches but all yield the same result.

File audioIn = new File("assets/file.wav");
byte [] byteArray = new byte[filesize];
FileInputStream fileInStream = new FileInputStream(audioIn);
fileInStream.read(byteArray);

Here's the debug data taken from individual bytes. The header information corresponds with what the Java methods have extracted before. From what I've read, the sound data should start at byte[44] however I'm getting the results below. The rest of the array is filled with 0s.

Byte 0: 82
Byte 1: 73
Byte 2: 70
Byte 3: 70
...
Byte 41: 97
Byte 42: 0
Byte 43: -68
Byte 44: -1
Byte 45: 1
Byte 46: 0
Byte 47: 0
...

It should also be noted that the header data will be discarded here as the WAVE information will be sent over beforehand. Thanks in advance for your help.

2
  • Do the bytes above match the contents of file.wave? Use a hex viewer (od -h on Unix/Linux/OSX) to verify. Commented Mar 19, 2012 at 23:51
  • 1) I would send the entire file (an extra 44 bytes at the head is going to make little difference. 2) You do realize that many sound samples start with '0 volume sound' before building up to the normal volume, right? Commented Mar 20, 2012 at 7:01

2 Answers 2

3

FileInputStream.read does not fill the byte array with data; it only reads what can be read in a single go. You would have to call it in a loop to read everything.

Alternatively you can use the DataInputStream.readFully method. If you are using Java 7 you could use Files.readAllBytes.

Sign up to request clarification or add additional context in comments.

Comments

1

You can also check out Apache/Commons IO library, there's some handy stuff in there for dealing with common I/O tasks like reading in an entire file into a byte array, or closing the input/output boilerplate stuff.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.