我正在开发一个项目,希望添加按键式对讲功能,我的客户端是Android
,服务器端使用Java
。我的方法是从AudioRecord
发送bytes
到服务器,然后将其广播给连接的客户端。
我的问题在于混合处理同时发送的不同客户端的data
时遇到麻烦。
以下是我在服务器上尝试过的方法:
static boolean status = true;
static int port = 1938;
static byte[] mixed_audio;
static byte[][] all_bytes;
static int client_count = 0;
static DatagramSocket socket;
static ArrayList<InetAddress> addresses;
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(port);
System.out.println("Listening. . .");
addresses = new ArrayList<>();
for(int x = 0; x < args.length; x++){
if(args[x].equals("-p")){
port = Integer.parseInt(args[x+1]);
}
}
byte[] receiveData = new byte[1400];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
socket = new DatagramSocket();
while (status == true) {
all_bytes = new byte[1400][1400];
mixed_audio = new byte[1400];
serverSocket.receive(receivePacket);
int a = addresses.indexOf(receivePacket.getAddress());
if(a < 0 ){
addresses.add(receivePacket.getAddress());
}
client_count++;
all_bytes[client_count] = receivePacket.getData();
new Thread(new ReceiveData(receivePacket.getData(), receivePacket.getAddress())).start();
}
}
public static class ReceiveData implements Runnable{
byte[] data;
InetAddress address;
public ReceiveData(byte[] b, InetAddress address){
this.data = b;
this.address = address;
}
@Override
public void run() {
try {
for(int i = 0; i < 1400; i++){
for(int j = 0; j < 1400; j++){
mixed_audio[j] += all_bytes[i][j];
}
}
if(client_count > 1){
int c=0;
for(int x = 0; x < 1400; x++){
mixed_audio[x] = (byte) (mixed_audio[x] / client_count + 1);
}
}else{
mixed_audio = data;
}
client_count--;
for(InetAddress add: addresses){
if(add != address){
DatagramPacket packet;
packet = new DatagramPacket(mixed_audio, mixed_audio.length, add, port);
socket.send(packet);
}
}
} catch (IOException ex) {
//Logger.getLogger(TeraMix.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
当只有一个客户端在通话时,音频输出清晰,但是当多个客户端同时开始通话时,音频输出变得非常不清晰。
我还尝试了使用我的混音音频算法在计算机上的文件上,并且它效果很好。我需要混合由不同客户端同时发送的数据包
。
我需要在不同的线程上处理客户端吗?我做错了吗? 这方面是否有更好的方法? 请在此指导我。谢谢!