/** * A class that encodes a Sound using an array of differences * between sound samples. It is lossless only if every * difference is in the range [-128..127]. * * @author Eugene Wallingford * @date November 7, 2006 */ import java.io.*; public class DiffSound { // ----- Instance variables ---------------------------------- private int firstSample; private byte[] differences; // ----- Constructors ---------------------------------------- /** * Initialize the DiffSound using a given first sample * and array of differences between adjacent samples. * @param sample the first sample in the sound [-32768..32767] * @param diffs an array of differences between samples */ public DiffSound( int sample, byte[] diffs ) { firstSample = sample; differences = diffs; } // ----- I/O methods ----------------------------------------- /** * Display to standard output the difference values * between locations start and end, inclusive. * @param start the location of the first value to display * @param end the location of the last value to display */ public void displayDifferences( int start, int end ) { for (int i = start; i < end; i++ ) System.out.println( differences[i] ); } /** * Write compressed object to a file of the given name, * in the media path directory * @param filename the short name of the file */ public void write( String filename ) { String fullname = FileChooser.getMediaPath( filename ); try { BufferedWriter file = new BufferedWriter( new FileWriter(fullname) ); file.write( ""+ firstSample ); file.newLine(); file.write( ""+ differences.length ); file.newLine(); for (int i = 0; i < differences.length; i++ ) { file.write( ""+ differences[i] ); file.newLine(); } file.close(); } catch (IOException e ) { } } // ----- Other methods --------------------------------------- /** * Deompresses the receiver as a Sound, reconstructing the array * of samples from its array of _differences_ between samples. * @return a Sound object */ public Sound decompress() { Sound fullSound = new Sound( 1 + differences.length ); int nextValue; fullSound.setSampleValueAt( 0, firstSample ); int lastValue = firstSample; for (int i = 1; i < fullSound.getLength(); i++ ) { nextValue = lastValue + differences[i-1]; fullSound.setSampleValueAt( i, nextValue ); lastValue = nextValue; } return fullSound; } }