Java Wave File I/O
The
WavFile class takes care of all the file IO for reading and writing audio data to and from wave files. The WavFile class provides methods for accessing wav file data using different java primitive types, these are long, int and double. It is up to the user to choose the correct type for the given wav file's sample resolution.This class reads the data from a text file created by the Arduino. As this is 8 bit recording all values are between 0-255. I need to investigate if scaling will be required to normalise the sound.
Creating the Wave file:
Before creating the wave file the length and duration of the recording must be calculated.
This is achieved by opening the text file, couting each sample and storign the last value, as it is the duration in miliseconds.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
numSamples++;
duration = Double.parseDouble(strLine)/1000;
}
numSamples--; // compstate for the legnth on the end
//Close the input stream
br.close();
Also, the sample rate must be calculated before preccding. sampleRate = (int) (numSamples / duration);
Now the wave file can be instantiated.
newWavFile(File file, int numChannels, long numFrames, int validBits, long sampleRate) throws IOException, WavFileExceptionThis method creates a new wav file for writing to. It writes header information to the wav file. Once this method has been called and a
WavFile instance retrieved, thewriteFrames methods can be used to write samples to the wav file.file : File output = new File(output.wav"); // specifies the output file
Again the data text file is opened however this time each value is added to the wav file
The last value is excluded as it is the length.
// Create a wav file with the name specified as the first argument
WavFile wavFile = WavFile.newWavFile(outfile, numChannels, numSamples, bitRate, sampleRate);
BufferedReader br = new BufferedReader(new FileReader(fileName));
String strLine;
//Read File Line By Line
int i = 0;
while (i <= numSamples) {
strLine = br.readLine();
i++;
//System.out.print(strLine);
int[] value = {Integer.parseInt(strLine)};
wavFile.writeFrames(value, 1);
}
//Close the input stream
br.close();
wavFile.close();
No comments:
Post a Comment