📄 udpcapture.java
字号:
/*
* UDPCapture.java
*
* Created on 2006年5月7日, 下午1:06
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package skyqq;
import javax.sound.sampled.*;
import java.net.*;
/**
* 抓取声音并发送
* @author wjhua
*/
public class UDPCapture implements Runnable{
TargetDataLine line;
Thread thread;
DatagramPacket pacToSend;
DatagramSocket soc;
String ip;
/** Creates a new instance of UDPCapture */
public UDPCapture(String ip) {
this.ip=ip;
}
public void start() {
thread = new Thread(this);
thread.setName("udpcapture");
thread.start();
}
public void stop() {
thread = null;
}
public void run() {
try {
soc = new DatagramSocket();
//建立输出流 此处可以加套压缩流用来压缩数据
} catch (Exception 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);
//TargetDataLine 接口是DataLine接口的一种,通过它就可以直接从音频硬件获取数据了
line.open(format, line.getBufferSize());
} catch (Exception ex) {
return;
}
byte[] data = new byte[1024];//跟下面的1024应保持一致
int numbytesread = 0;
line.start();
while (thread != null) {
numbytesread = line.read(data, 0, 1024);
try {
pacToSend = new DatagramPacket(data,data.length,
InetAddress.getByName(ip),20001);
soc.send(pacToSend);//写入网络流
} catch (Exception ex) {
break;
}
}
line.stop();
line.close();
line = null;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -