package cnrg.itx.datax.devices;

import javax.media.sound.sampled.*;
import cnrg.itx.datax.*;
import java.io.*;

//This is a test of Sun's JavaSound. I tested it with build 086 on NT and had problems with simultaneous play
//and record. 
//NOTE: as of 8/16, Java Sound is not ready for prime time. Give this a try with a build after #086.

public class JMicrophoneSource extends Thread implements Source{
	
	
	private static int BUFFER_SIZE = 100;
	
	private cnrg.itx.datax.Channel channel;
	
	private InputDevice soundIn;
	
	private InputChannel mic;
	
	/** 
	 * is the feeder thread running?
	 */
	private boolean running = true;
	
	public JMicrophoneSource(cnrg.itx.datax.Channel ch) throws DataException{
		channel = ch;
		
		AudioFormat itxAudio = new AudioFormat(AudioFormat.Encoding.PCM_UNSIGNED,8000,8,1,8,8000); 

		soundIn = AudioSystem.getInputDevice(null); //get the system's default sound in device
		try {
			mic = soundIn.getInputChannel(itxAudio, BUFFER_SIZE);
			
		} catch (AudioUnavailableException e2) {
			System.err.println("AudioUnavailableException: " + e2);
			throw new cnrg.itx.datax.DataException(e2.getMessage());
		}
	}
	
	
	
	
	
	public boolean mute(boolean state) {
		return true;
	}
	
	public void close() {
		running = false;
	}
	
	public Stats getStatistics () 
	{ 
		return new Stats();
	}
	
	/**
	 * Returns a collection of properties supported.
	 */ 
	public PropertiesCollection getProperties() throws DataException
	{
		return null;
	}

	/**
	 * Sets the given properties collection into the device (local);
	 */
	public void setProperties(PropertiesCollection pc) throws DataException
	{
	}

	/**
	 * Interface to set the given properties collection into the device. WOrks under the 
	 * assumption that this is the properties collection of the peer.
	 */
	public void setPeerProperties(PropertiesCollection pc) throws DataException
	{
	}
	
	public void run() {
		byte[] data = new byte[64];
		while (running){
			mic.read(data,0,data.length);
			channel.push(data);
		}
	}
	
}

