Android ilbc 语音对话示范(五)接收端处理
介绍了 “代码结构”,“程序流程”,以及”发送方的处理”,现在就把接收方的处理流程做个介绍;
如上图所示,接收方的操作有三个类:AudioDecoder(负责解码),AudioPlayer(负责播放解码后的音频),
AudioReceiver(负责从服务器接收音频数据包),这三个类的流程在第三篇中有详细的介绍。
1.AudioReceiver代码:
AudioReceiver使用UDP方式从服务端接收音频数据,其过程比较简单,直接上代码:
package xmu.swordbearer.audio.receiver;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import xmu.swordbearer.audio.MyConfig;
import android.util.Log;
public class AudioReceiver implements Runnable {
String LOG = "NET Reciever ";
int port = MyConfig.CLIENT_PORT;// 接收的端口
DatagramSocket socket;
DatagramPacket packet;
boolean isRunning = false;
private byte[] packetBuf = new byte[1024];
private int packetSize = 1024;
/*
* 开始接收数据
*/
public void startRecieving() {
if (socket == null) {
try {
socket = new DatagramSocket(port);
packet = new DatagramPacket(packetBuf, packetSize);
} catch (SocketException e) {
}
}
new Thread(this).start();
}
/*
* 停止接收数据
*/
public void stopRecieving() {
isRunning = false;
}
/*
* 释放资源
*/
private void release() {
if (packet != null) {
packet = null;
}
if (socket != null) {
socket.close();
socket = null;
}
}
public void run() {
// 在接收前,要先启动解码器
AudioDecoder decoder = AudioDecoder.getInstance();
decoder.startDecoding();
isRunning = true;
try {
while (isRunning) {
socket.receive(packet);
// 每接收一个UDP包,就交给解码器,等待解码
decoder.addData(packet.getData(), packet.getLength());
}
} catch (IOException e) {
Log.e(LOG, LOG + "RECIEVE ERROR!");
}
// 接收完成,停止解码器,释放资源
decoder.stopDecoding();
release();
Log.e(LOG, LOG + "stop recieving");
}
}
2.AudioDecoder代码:
解码的过程也很简单,由于接收端接收到了音频数据,然后就把数据交给解码器,所以解码的主要工作就是把接收端的数
据取出来进行解码,如果解码正确,就将解码后的数据再转交给AudioPlayer去播放,这三个类之间是依次传递的 :
AudioReceiver---->AudioDecoder--->AudioPlayer
下面代码中有个List变量 private List<AudioData> dataList = null; 这个就是用来存放数据的,每次解码时,dataList.remove(0),
从最前端取出数据进行解码:
package xmu.swordbearer.audio.receiver;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import xmu.swordbearer.audio.AudioCodec;
import xmu.swordbearer.audio.data.AudioData;
import android.util.Log;
public class AudioDecoder implements Runnable {
String LOG = "CODEC Decoder ";
private static AudioDecoder decoder;
private static final int MAX_BUFFER_SIZE = 2048;
private byte[] decodedData = new byte[1024];// data of decoded
private boolean isDecoding = false;
private List<AudioData> dataList = null;
public static AudioDecoder getInstance() {
if (decoder == null) {
decoder = new AudioDecoder();
}
return decoder;
}
private AudioDecoder() {
this.dataList = Collections
.synchronizedList(new LinkedList<AudioData>());
}
/*
* add Data to be decoded
*
* @ data:the data recieved from server
*
* @ size:data size
*/
public void addData(byte[] data, int size) {
AudioData adata = new AudioData
补充:移动开发 , Android ,