Mercurial > hg > ishara
diff audio/java/AudioSource.java @ 0:672052bd81f8
Initial partial import.
author | samer |
---|---|
date | Wed, 19 Dec 2012 22:38:28 +0000 |
parents | |
children | 63cefb01cbab |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/audio/java/AudioSource.java Wed Dec 19 22:38:28 2012 +0000 @@ -0,0 +1,73 @@ +/* + * AudioSource.java + * + * Copyright (c) 2012, Samer Abdallah + * All rights reserved. + * + * This software is provided AS iS and WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +package samer.audio.alt; +import javax.sound.sampled.AudioFormat; + +public abstract class AudioSource +{ + AudioFormat format; + + public AudioSource(AudioFormat f) { format=f; } + + public AudioFormat getFormat() { return format; } + + public abstract void dispose(); + public abstract void start(); + public abstract void stop(); + public abstract int read(byte [] bbuf, int offset, int len) throws Exception; + + public Reader reader(int len) { + return new Reader(len,format.getSampleSizeInBits()/8); + } + + public class Reader { + byte[] bbuf; + double[] dbuf; + int rem, numbytes, bps; + Converter conv; + + public Reader(int numsamples, int bps) { + this.bps=bps; + numbytes=bps*numsamples; + bbuf=new byte[numbytes]; + dbuf=new double[numsamples]; + conv=getConverter(bbuf,dbuf,bps); + rem=0; + } + + public int unread() { return rem; } + public double[] next() throws Exception { + int rem=numbytes, pos=0; + while (rem>0) { + int bytesRead=read(bbuf, 0, rem); + if (bytesRead<=0) { this.rem=rem/bps; return dbuf; } + int count=bytesRead/bps; + conv.convert(pos,count); + pos+=count; rem-=bytesRead; + } + return dbuf; + } + } + + protected interface Converter { public void convert(int pos, int count); } + protected static Converter getConverter(final byte [] bbuf,final double [] dbuf,final int bps) { + switch (bps) { + case 1: return new Converter() { public void convert(int pos, int count) { Util.byteToDouble(bbuf,dbuf,pos,count); } }; + case 2: return new Converter() { public void convert(int pos, int count) { Util.shortToDouble(bbuf,dbuf,pos,count); } }; + case 3: return new Converter() { public void convert(int pos, int count) { Util.mediumToDouble(bbuf,dbuf,pos,count); } }; + case 4: return new Converter() { public void convert(int pos, int count) { Util.intToDouble(bbuf,dbuf,pos,count); } }; + } + throw new Error("Unrecognised sample format"); + } + public static void print(String msg) { System.out.println(msg); } +} +