我正在开发一个项目,我想添加一键通功能,我有android
客户端和java
服务器.我所做的是送bytes
从AudioRecord
到我的服务器和广播回连接的客户端.
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 ArrayListaddresses; 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); } } }
只有一个客户端正在通话时的音频输出是清晰的,但当多个客户端同时开始通话时的音频输出变得非常不清楚.
我还尝试了我的算法,通过在PC上的文件上使用它来混合音频,它运行良好.我需要的是混合data packets
由不同客户同时发送的.
我是否需要在不同的线程上处理客户端?我做错了吗?这有更好的方法吗?请指导我这个.谢谢!