diff src/samer/audio/LineSource.java @ 0:bf79fb79ee13

Initial Mercurial check in.
author samer
date Tue, 17 Jan 2012 17:50:20 +0000
parents
children 5df24c91468d
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/samer/audio/LineSource.java	Tue Jan 17 17:50:20 2012 +0000
@@ -0,0 +1,93 @@
+/*
+ *	LineSource.java
+ *
+ *	Copyright (c) 2000, Samer Abdallah, King's College London.
+ *	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;
+import  samer.core.*;
+import  samer.tools.*;
+import  java.io.*;
+import  javax.sound.sampled.*;
+
+/**
+	An AudioSource that reads from the sound card in real time.
+	Uses a standard JavaSound TargetDataLine to get data.
+	However, an alternative DataLine can be supplied instead.
+	Audio format is determined by current environment--see
+	VLine.
+	<p> Object is a Viewable, and is called "linein". Node is
+	created in current context, ie with a parent determined by
+	current Environment.
+	@see samer.core.AudioSource
+*/
+
+public class LineSource extends VLine implements AudioSource
+{
+	private TargetDataLine	line;
+	private AudioFormat	fmt;
+	private int          bufsize=0;
+
+	/** Create LineSource reading from given TargetDataLine */
+	public LineSource(TargetDataLine l,AudioFormat f) throws Exception {
+		super("linein"); line=l; fmt=f;
+	}
+
+	public void setBufferSize(int b) { bufsize=b; }
+
+	public DataLine getLine() { return line; }
+	public boolean  isOpen() { return line.isOpen(); }
+
+	/** Open using default format */
+	public void openImpl() throws Exception {
+		if (bufsize==0) line.open(fmt); else line.open(fmt,bufsize);
+	}
+
+	public void closeImpl() throws Exception { line.close(); }
+
+	public Task reader(final double dbuf[], final int off, final int len) {
+		return new Reader(2*len) {
+			public void run() throws Exception {
+				super.run();	Util.shortToDouble(buf,dbuf,off,len);
+			}
+		};
+	}
+
+	public Task reader(final float dbuf[], final int off, final int len) {
+		return new Reader(2*len) {
+			public void run() throws Exception {
+				super.run();	Util.shortToFloat(buf,dbuf,off,len);
+			}
+		};
+	}
+
+
+	protected class Reader implements Task {
+		byte buf[];
+		int		size;
+
+		public Reader(int bufsize) { size=bufsize; buf=new byte[size]; }
+
+		public void starting() { start(); }
+		public void stopping() { stop(); }
+		public void dispose() {}
+		public void run() throws Exception {
+			if (line.read(buf,0,size)<=0) throw new EOFException();
+			changed();
+		}
+	}
+
+	public static DataLine.Info lineInfo(AudioFormat fmt) {
+		return new DataLine.Info( TargetDataLine.class, fmt); 
+	}
+
+	public static DataLine.Info lineInfo(AudioFormat fmt, int bufsize) {
+		return new DataLine.Info( TargetDataLine.class, fmt, bufsize); 
+	}
+}
+