samer@0: /* samer@0: * LineSource.java samer@0: * samer@0: * Copyright (c) 2012, Samer Abdallah, King's College London. samer@0: * All rights reserved. samer@0: * samer@0: * This software is provided AS iS and WITHOUT ANY WARRANTY; samer@0: * without even the implied warranty of MERCHANTABILITY or samer@0: * FITNESS FOR A PARTICULAR PURPOSE. samer@0: */ samer@0: samer@46: package ishara.audio; samer@0: import javax.sound.sampled.*; samer@0: import java.io.*; samer@0: samer@0: samer@0: /** samer@0: An AudioSource that reads from the sound card in real time. samer@0: Uses a standard JavaSound TargetDataLine to get data. samer@0: However, an alternative DataLine can be supplied instead. samer@0: */ samer@0: samer@0: public class LineSource extends AudioSource samer@0: { samer@0: private TargetDataLine line; samer@0: private int bufsize; samer@0: samer@0: /** Create LineSource reading from given TargetDataLine */ samer@0: public LineSource(AudioFormat f, int bufsize) throws Exception { samer@0: this((TargetDataLine)AudioSystem.getLine(lineInfo(f,bufsize)),f,bufsize); samer@0: } samer@0: samer@0: public LineSource(TargetDataLine l,AudioFormat f,int bs) throws Exception { samer@0: super(f); line=l; samer@0: print("Opening audio data line: "+f); samer@0: if (bs==0) line.open(f); else line.open(f,bs); samer@0: bufsize=line.getBufferSize(); samer@0: } samer@0: samer@0: public void dispose() { samer@0: print("Closing audio data line"); samer@0: try { line.close(); } samer@0: catch (Exception ex) { samer@0: print("line failed to close: "+ex); samer@0: } samer@0: } samer@0: samer@0: public void start() { line.flush(); line.start(); } samer@0: public void stop() { line.stop(); } samer@0: public int read(byte [] buf, int offs, int len) throws Exception { samer@0: return line.read(buf,offs,len); samer@0: } samer@0: samer@0: public DataLine getLine() { return line; } samer@0: public void check() { print("LineSource buffer room available: "+(bufsize-line.available())); } samer@0: public String toString() { return "LineSource("+line.getFormat()+")"; } samer@0: samer@0: public static DataLine.Info lineInfo(AudioFormat fmt) { return lineInfo(fmt,0); } samer@0: public static DataLine.Info lineInfo(AudioFormat fmt, int bufsize) { samer@0: if (bufsize==0) samer@0: return new DataLine.Info( TargetDataLine.class, fmt); samer@0: else samer@0: return new DataLine.Info( TargetDataLine.class, fmt, bufsize); samer@0: } samer@0: } samer@0: