I'm interested in learning about audio file manipulation in Java, so, after researching some background on the .wav file format, I wrote a simple program to read in a .wav file, place it into a byte array, and then write that array to a new .wav file. The output file isn't a copy of the input file, however. For example, when I open the two .wav files in a text editor (Notepad++), the original will begin by saying "RIFF" as it should, but the copy starts out with a series of null characters. Can anybody tell me what I'm doing wrong?
Here is my code:
package funwithwavs2;
import javax.sound.sampled.*;
import java.io.*;
public class FunWithWavs2 {
public static void main(String[] args) {
int x;
byte[] wavBytes=new byte[100000000];
try {
AudioInputStream ais=AudioSystem.getAudioInputStream(new File("Centerfold.wav"));
while((x=ais.read(wavBytes))>0) {
System.out.println("X: "+x);
}
writeToFile(wavBytes);
}
catch (Exception ex) {
System.err.println("Error reading WAV file.");
ex.printStackTrace();
}
}
public static void writeToFile(byte[] b) {
File file=new File ("centerfold3.wav");
try {
if(!file.exists()) {
file.createNewFile();
}
FileWriter fw=new FileWriter(file.getAbsoluteFile());
BufferedWriter bw=new BufferedWriter(fw);
for(int i=0;i<b.length;i++) {
bw.write(b[i]);
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks!
Edit to Reflect Comments Below: I switched my input declaration to the the code snippet below, but it gives me a mark/reset not supported exception.
InputStream input=new FileInputStream("Centerfold.wav");
AudioInputStream ais=AudioSystem.getAudioInputStream(input);
The crux of my issue isn't writing to the output .wav file. It's that the bytes that I read from the input file aren't what I expect them to be.
while((x2=ais.read(wavBytes))>0) {
System.out.println("X2: "+x2);
}
for(int i=0;i<36;i++) {
System.out.println(i+": "+wavBytes[i]);
}
Looking at this code, I would expect the first four characters that are printed out to be the ASCII values for: R I F F, per the .wav file format. What I get, however, is a series of 0s, the ASCII value for a NULL. Why is there this discrepancy? Am I fundamentally misunderstanding something about either the .wav file format or the functionality of the javax.sound.sampled classes?