import java.awt.Frame;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Random;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
/**
* Title: VoiceChat Description: 音频捕捉(录音程序) Copyright: Copyright (c) 2001
* Company:
*
* @author 你猜!
* @version 1.0
*/
class Capture implements Runnable {
TargetDataLine line;
Thread thread;
Socket s;
BufferedOutputStream captrueOutputStream;
private DataCanvas canvas;
Capture(Socket s) {// 构造器 取得socket以获得网络输出流
this.s = s;
}
public void start() {
thread = new Thread(this);
thread.setName("Capture");
thread.start();
canvas = new DataCanvas();
Frame f;
f = new Frame("Capture");
f.setSize(400, 300);
f.add(canvas);
f.setVisible(true);
Thread t = new Thread(canvas);
t.start();
}
public void stop() {
thread = null;
}
public void run() {
try {
captrueOutputStream = new BufferedOutputStream(s.getOutputStream());// 建立输出流
// 此处可以加套压缩流用来压缩数据
} catch (IOException ex) {
return;
}
AudioFormat format = new AudioFormat(8000, 16, 2, true, true);// AudioFormat(float
// sampleRate,
// int
// sampleSizeInBits,
// int
// channels,
// boolean
// signed,
// boolean
// bigEndian)
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
try {
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
} catch (Exception ex) {
return;
}
byte[] data = new byte[1024];// 此处的1024可以情况进行调整,应跟下面的1024应保持一致
int numBytesRead = 0;
line.start();
while (thread != null) {
numBytesRead = line.read(data, 0, 1024);// 取数据(1024)的大小直接关系到传输的速度,一般越小越快,
try {
captrueOutputStream.write(data, 0, numBytesRead);// 写入网络流
int i = 0;
for (byte b : data) {
// System.out.print(b + ",");
// if (i == 10) {
// System.out.println();
// i = 0;
// }
// i++;
LinkedList dl = canvas.getDataList();
dl.removeLast();
dl.addFirst(b);
}
} catch (Exception ex) {
break;
}
}
line.stop();
line.close();
line = null;
try {
captrueOutputStream.flush();
captrueOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(3000);
while (true) {
Socket s = ss.accept();
System.out.println("开始连接");
// Thread t=new Thread(new Capture(s));
// t.start();
new Capture(s).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}