Android音訊實時傳輸與播放(一)
阿新 • • 發佈:2018-11-04
服務端共開放兩個埠,一個udp上行埠用來接收amr音訊流,另一個tcp下行埠用來發送amr音訊流。
我這裡寫的服務端實現了組播的功能,即一個人在錄音,可以同時讓很多人同時聽到。
簡而言之,服務端做的唯一一件事情就是轉發音訊流,囧rz。。。
在這裡,我只貼出一部分程式碼,後面我會上傳資源供大家下載。
接收udp傳送的音訊碼流:
[java] view plain copy
- while (isServerRunning()) {
- try {
- DatagramPacket pack = new DatagramPacket(data, data.length);
- udpServer.receive(pack);
- addPacketToBuffer(new
- } catch (Exception e) {
- System.out.println(e.toString());
- }
- }
用tcp轉發收到的音訊流:
[java] view plain copy
- public void sendDataToAllClient() throws Exception {
- if (isBufferEmpty() || clientList.size() <= 0) {
- return;
- }
- boolean bufEmpty = isBufferEmpty();
- byte[] block = takeAwayFirstFrame();
- ArrayList<Integer> disConnectClient = new ArrayList<Integer>();
- for (int ix = 0; ix < clientList.size(); ++ix) {
- Client client = clientList.get(ix);
- Socket clientSocket = client.getSocket();
- if (clientSocket.isConnected()) {
- try {
- if (!bufEmpty) {
- if (block == null) {
- continue;
- }
- OutputStream output = clientSocket.getOutputStream();
- output.write(block);
- output.flush();
- }
- } catch (Exception err) {
- disConnectClient.add(ix);
- }
- } else {
- disConnectClient.add(ix);
- }
- }
- for (int ix = 0; ix < disConnectClient.size(); ++ix) {
- int index = disConnectClient.get(ix);
- clientList.remove(index);
- }
- disConnectClient.clear();
- disConnectClient = null;
- block = null;
- }