I'm doing a project in java which requires me to encrypt a wave file. So, is there a straight forward process to convert a wave file into binary and back? I'll be applying an encryption algorithm on the binary data.
Asked
Active
Viewed 1.3k times
2
-
1I mean bits....series of 1's and 0's – Uday Kanth Jun 15 '11 at 13:31
-
1@Uday: Yes, I realise that! What I mean is, what do you want that binary to represent? A file is already a series of 1s and 0s. Why can't you just read the file into a `byte[]`? Why does it matter that it's specifically a .wav file? – Oliver Charlesworth Jun 15 '11 at 13:33
-
Reading a binary file into a char array is probably a very stupid thing to do. – jarnbjo Jun 15 '11 at 13:36
-
@jarnbjo: Yes, my mistake. I meant `byte` array... – Oliver Charlesworth Jun 15 '11 at 13:42
-
You'll find most things in a computer are binary already. :) – Joe Jun 15 '11 at 13:46
4 Answers
4
Most languages have utilities to read and write files in binary mode. If you happen to be on a Linux system, it's the same as character mode. In any case, it's not a matter of "converting" to binary, just a different method of reading it.

jpm
- 3,165
- 17
- 24
4
Yes.
File file = new File("music.wav");
byte[] data = new byte[file.length()];
FileInputStream in = new FileInputStream(file);
in.read(data);
in.close();
//encrypt data
FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
Of course assuming it's still a valid wav file after you play around with the data.

John
- 2,395
- 15
- 21
-
2There is no guarantee that in.read(data) will read all of the file. http://download.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read(byte[]) states that it will read _up to_ b.length bytes. – Paul Cager Jun 15 '11 at 13:39
-
Yes, but that assumes the array isn't big enough, which it is. File.length() is the length of a file. However, if you want to be careful you could compare the value returned by read to the size of the file to be sure. – John Jun 15 '11 at 13:42
-
2@Trey - no, it has nothing to do with the size of the array. it has to do with the stream implementation. you should _never_ assume that `read()` will fill your array. – jtahlborn Jun 15 '11 at 14:10
-
Thanks!! this worked!! :) I was unnecessarily meddling with AudioInputStream until now! – Uday Kanth Jun 15 '11 at 14:27
-
Ummm I'm getting the original file back now...of course i didnt apply any encryption as of yet, I just converted the bytes to bits and then back to bytes and then back to wave file..so now do I need to bother about read() not reading the entire file?? – Uday Kanth Jun 15 '11 at 14:30
-
1@Uday Kanth - Yes, you should be concerned about read() not reading the complete file. It will probably work for small files, might work for larger files but it is not guaranteed. You can either read in a loop or use something like http://commons.apache.org/io/api-1.3.2/index.html IOUtils. – Paul Cager Jun 15 '11 at 14:56
-
-