public class UdpDataReceiver implements Runnable {
private boolean isRunning = true;
private int port = -1;
private DatagramSocket socket;
public UdpDataReceiver(int port) {
this.port = port;
}
public void stop() {
isRunning = false;
socket.close();
}
@Override
public void run() {
try {
socket = new DatagramSocket(port);
System.out.println(" + Listening for UDP data on port " + port + ".");
} catch (Exception e) {
e.printStackTrace();
}
// Size of data buffer is insignificant; it just needs to be big enough to hold the UDP packet (or it will be truncated).
byte[] data = new byte[512];
DatagramPacket packet = new DatagramPacket(data, data.length);
String file = null;
FileOutputStream fos = null;
try {
// For now we'll just dump to a file.
file = "C:\\tmp\\" + System.currentTimeMillis() + ".raw";
fos = new FileOutputStream(file);
while (isRunning) {
try {
socket.receive(packet);
} catch (SocketException se) {
// If we're just trying to tell the socket we're done, we'll get a SocketException.
if (isRunning) {
se.printStackTrace();
}
}
if (packet.getLength() > 12) {
// Strip off 12 bytes of header data.
fos.write(packet.getData(), packet.getOffset() + 12, packet.getLength() - 12);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.flush();
fos.close();
convertULawFileToWav(file);
} catch (Exception e) {
}
System.out.println(" + Closed port " + port + " and wrote UDP packets to file: " + file);
}
}
public static void convertULawFileToWav(String filename) {
File file = new File(filename);
if (!file.exists())
return;
try {
long fileSize = file.length();
int frameSize = 160;
long numFrames = fileSize/frameSize;
AudioFormat audioFormat = new AudioFormat(Encoding.ULAW, 8000, 8, 1, frameSize, 50, true);
AudioInputStream audioInputStream = new AudioInputStream(new FileInputStream(file), audioFormat, numFrames);
AudioSystem.write(audioInputStream, Type.WAVE, new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 3) + "wav"));
} catch (IOException e) {
e.printStackTrace();
}
}
// For testing...
public static void main(String[] args) throws InterruptedException {
UdpDataReceiver r1 = new UdpDataReceiver(65337);
new Thread(r1).start();
// Send data...
Thread.sleep(30000);
r1.stop();
}
}
shareeditflag
내가 [Live555 도서관]에서 살펴 봐야 당신을 제안 (http://www.live555.com /). 샘플 프로그램부터 시작하십시오. 조금은 분명히 정리할 수있을 것입니다. – RohitMat
만족스러운 답변이 없습니다. 참조 코드가 추악합니다. 타이밍에 대해 아무 말도하지 않습니다. 하지만 고마워. 내가 선택한 게 틀림 없어. –