1

I am using some algorithms which need data represented in array of bytes it is no problem when I am working on text files but I don't know how to put a sound file in a that kind of array. I don't have specified extension of that sound file, so it can be whatever is the easiest. So: How to put a sound file to a byte array in Java?

Thank you.

11
  • byte[] bytes = new byte[length];? your question isn't clear. do you not know how to create bytes array and java syntax? Commented Sep 25, 2012 at 23:31
  • What is unclear? I have a SOUND(not text) file in a specified directory and I would like to put it into array of bytes? Commented Sep 25, 2012 at 23:35
  • 1
    What format are you getting the sound in? The WAVE format is usually the easist to work with. Commented Sep 25, 2012 at 23:37
  • 1
    Do you need to put the sound samples into the array to process later, or do you just need to read a generic file into a bytearray? Commented Sep 25, 2012 at 23:40
  • 1
    basically, there are no different between text file and any other files . they are all stream of bytes. the only difference is in the sequence or pattern of the bytes. Commented Sep 25, 2012 at 23:41

2 Answers 2

3

Alternatively, if you can use Apache common IO library, the FileUtils class contains a readFileToByteArray method for reading a file into a byte array in one line:

byte[] bytes = FileUitls.readFileToByteArray(file);
Sign up to request clarification or add additional context in comments.

Comments

3

So: How to put a sound file to a byte array in Java?

File f = new File(soundFilePath, soundFileName);
byte[] soundFileByteArray = new byte[f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(soundFileByteArray);

3 Comments

Is it that simple?Don't you have to put the read inside a while in order to check whether the file ends?
@giannosfor if you allocate enough length for the array, then it reads the whole file.
@gigadot f.length() returns long while new byte[] expects int, changing it to new byte[(int) f.length()] is okay? since there is possibility of losing some data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.