view audio/java/AudioSource.java @ 61:eff6bddf82e3 tip

Finally implemented perceptual brightness thing.
author samer
date Sun, 11 Oct 2015 10:20:42 +0100
parents 63cefb01cbab
children
line wrap: on
line source
/*
 *	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 ishara.audio;
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); }
}