/**24.03.2008
* Jan Gunnar Gleixner
* BWINF
*
*
*/
package horcher.sound;
import horcher.Fehler;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class WaveFileInputStream {
int kanalanzahl;
int samplerate;
int bytetiefe;
int lange;
int kanal;
private int pos = 1;
BufferedInputStream inSB;
File file;
public WaveFileInputStream(final File file, final int kanal) throws Fehler,
IOException {
this.file = file;
this.inSB = new BufferedInputStream(new FileInputStream(this.file));
final int hader[] = new int[12];
for (int i = 0; i < hader.length; i++)
hader[i] = this.inSB.read();
int tmp=0;
while(tmp!=544501094){
tmp/=256;
tmp+=256*256*256*this.inSB.read();
}
tmp=this.inSB.read()+256*this.inSB.read()+256*256*this.inSB.read()+256*256*256*this.inSB.read();
final int fmt[]= new int[tmp];
for (int i = 0; i < fmt.length; i++)
fmt[i] = this.inSB.read();
if ((fmt[0] != 1) | (fmt[1] != 0))
throw new Fehler("fDatenformat");
this.kanalanzahl = fmt[2] + 256 * fmt[3];
this.samplerate = fmt[4] + 256 * fmt[5] + 65536 * fmt[6] + 16777216* fmt[7];
this.bytetiefe = (fmt[14] + 256 * fmt[15]) / 8;
if (kanal >= this.kanalanzahl)
throw new Fehler("fKanalzahl");
this.kanal = kanal;
long tmp2=0;
while(tmp2!=1635017060){
tmp2/=256;
tmp2+=256*256*256*this.inSB.read();
}
this.lange=this.inSB.read()+256*this.inSB.read()+256*256*this.inSB.read()+256*256*256*this.inSB.read();
this.lange = this.lange / this.kanalanzahl / this.bytetiefe;
}
public void close() throws IOException {
this.inSB.close();
}
public double read() throws IOException {
double e = 0;
int temp;
this.inSB.skip(this.kanal * this.bytetiefe);
if (this.pos >= this.lange)
return 0;
for (int b = 0; b < this.bytetiefe; b++) {
temp = this.inSB.read();
e = (e + temp * Math.pow(256, b));
}
if (e >= Math.pow(256, this.bytetiefe) / 2)
e = (e - Math.pow(256, this.bytetiefe));
this.inSB.skip((this.kanalanzahl - this.kanal - 1) * this.bytetiefe);
this.pos++;
return e;
}
public double[] read(final int length) throws IOException {
final double[] e = new double[length];
for (int i = 0; i < length; i++)
e[i] = this.read();
return e;
}
public void reset() throws IOException {
this.inSB = new BufferedInputStream(new FileInputStream(this.file));
this.inSB.skip(44);
long tmp2=0;
while(tmp2!=1635017060){
tmp2/=256;
tmp2+=256*256*256*this.inSB.read();
}
}
public long skip(final long n) throws IOException {
return this.inSB.skip(n * this.bytetiefe * this.kanalanzahl);
}
}