import java.net.*; import javax.sound.sampled.*; public class Phone { public static final AudioFormat FORMAT = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0f, 16, 1, 2, 8000.0f, true); public static final int PORT = 6000; public static void main(String[] args) { new Phone(args); } public Phone(String[] args) { DatagramSocket socket = null; DatagramPacket packet = new DatagramPacket(new byte[]{1}, 1); InetAddress remote = null; try { if (args.length == 0) { System.out.println("Waiting for partner..."); socket = new DatagramSocket(PORT); socket.receive(packet); socket.connect(packet.getAddress(), PORT); } else { socket = new DatagramSocket(PORT); socket.connect(InetAddress.getByName(args[0]), PORT); } } catch(Exception e) { System.out.println(e); } System.out.println("Connected to partner..."); new Recorder(socket); new Player(socket); } } class Recorder extends Thread { private TargetDataLine line = null; private DatagramSocket socket = null; private InetAddress address= null; public Recorder(DatagramSocket socket) { this.socket = socket; address = socket.getInetAddress(); start(); } public void run() { DataLine.Info info = new DataLine.Info(TargetDataLine.class, Phone.FORMAT); try { line = (TargetDataLine)AudioSystem.getLine(info); line.open(Phone.FORMAT, line.getBufferSize()); } catch (Exception e) { System.out.println(e); } int frameSizeInBytes = Phone.FORMAT.getFrameSize(); int bufferLengthInFrames = line.getBufferSize() / 8; int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes; int minPacketSize = (int)(bufferLengthInBytes / 10.5); byte[] data; int bytesAvailable; line.start(); System.out.println("Record started..."); while(true) { // Send data only when we have a buffer of at least 50% if ((bytesAvailable = line.available()) >= minPacketSize) { data = new byte[bytesAvailable]; line.read(data, 0, bytesAvailable); try { socket.send(new DatagramPacket(data, bytesAvailable)); } catch(Exception e) { System.out.println(e); } } } /* line.stop(); line.flush(); line.close(); line = null; */ } } class Player extends Thread { public final int BUFFER = 8000; private SourceDataLine line = null; private DatagramSocket socket = null; public Player(DatagramSocket socket) { this.socket = socket; start(); } public void run() { DataLine.Info info = new DataLine.Info(SourceDataLine.class, Phone.FORMAT); try { line = (SourceDataLine)AudioSystem.getLine(info); line.open(Phone.FORMAT, BUFFER); } catch(Exception e) { System.out.println(e); } line.start(); DatagramPacket packet = new DatagramPacket(new byte[65536], 65536); System.out.println("Play started..."); while(true) { try { socket.receive(packet); } catch(Exception e) { System.out.println(e); } line.write(packet.getData(), 0, packet.getLength()); packet = new DatagramPacket(new byte[65536], 65536); //yield(); } /* line.stop(); line.flush(); line.close(); line = null; */ } }