2

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.

Uday Kanth
  • 361
  • 3
  • 9
  • 16

4 Answers4

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
  • 2
    There 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
  • Would using a ByteArrayOutputStream help? – Uday Kanth Jun 15 '11 at 15:06
  • @Paul how do I import those packages into my program? – Uday Kanth Jun 15 '11 at 15:12
1

Try the Java Wav IO library.

Karl-Bjørnar Øie
  • 5,554
  • 1
  • 24
  • 30
0

you could try the plugin : JLayer

shenju
  • 29
  • 3