我有一个问题,我已将 MediaLocator 设置为麦克风输入,然后创建了 Player。我需要从麦克风中获取声音,将其编码为一些质量较低的流,然后通过 UDP 将其作为数据报包发送。这是代码,我在网上找到了大部分代码并将其改编为我的应用程序:
public class AudioSender extends Thread {
private MediaLocator ml = new MediaLocator("javasound://44100");
private DatagramSocket socket;
private boolean transmitting;
private Player player;
TargetDataLine mic;
byte[] buffer;
private AudioFormat format;
private DatagramSocket datagramSocket(){
try {
return new DatagramSocket();
} catch (SocketException ex) {
return null;
}
}
private void startMic() {
try {
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0F, 16, 2, 4, 8000.0F, true);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
mic = (TargetDataLine) AudioSystem.getLine(info);
mic.open(format);
mic.start();
buffer = new byte[1024];
} catch (LineUnavailableException ex) {
Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex);
}
}
private Player createPlayer() {
try {
return Manager.createRealizedPlayer(ml);
} catch (IOException ex) {
return null;
} catch (NoPlayerException ex) {
return null;
} catch (CannotRealizeException ex) {
return null;
}
}
private void send() {
try {
mic.read(buffer, 0, 1024);
DatagramPacket packet =
new DatagramPacket(
buffer, buffer.length, InetAddress.getByName(Util.getRemoteIP()), 91);
socket.send(packet);
} catch (IOException ex) {
Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
player = createPlayer();
player.start();
socket = datagramSocket();
transmitting = true;
startMic();
while (transmitting) {
send();
}
}
public static void main(String[] args) {
AudioSender as = new AudioSender();
as.start();
}
}
当我运行接收器类时,唯一发生的事情就是我从发送器类听到这个播放器。而且我似乎看不到 TargetDataLine 和 Player 之间的联系。基本上,我需要获取声音格式播放器,并以某种方式将其转换为字节[],因此我可以将其作为数据报发送。有任何想法吗?一切都是可以接受的,只要它有效:)