任务是通过一个线程中的套接字广播声音,另一个线程通过同一个套接字发送字符串。结果应该在客户端读取。所有这些我通过DataInputStream和DataOutputStream以及一个字节数组来完成。 如果数据通过单个线程传输,则接收和传输数据是正常的。但是如果你在传输声音流的过程中发送一个文本字符串,就会产生数据在堆中混合的感觉,因为声音会破裂,而且这些行也无法获得。 有没有猜测为什么会发生这种情况?
这是我的代码的小样本:
(文字发送)
public void sendMessage(byte[] msg, int key) {
OutputStream mOutputStream;
try {
Socket socket = getSocket();
if (socket == null) {
Log.d(CLIENT_TAG, "Socket is null, wtf?");
} else if (socket.getOutputStream() == null) {
Log.d(CLIENT_TAG, "Socket output stream is null, wtf?");
}
mOutputStream = getSocket().getOutputStream();
DataOutputStream dos = new DataOutputStream(mOutputStream);
dos.writeUTF("#@@#");
dos.writeInt(key);
dos.writeInt(msg.length);
dos.flush();
dos.write(msg);
dos.flush();
logD("MESSAGE " + msg.length);
} catch (UnknownHostException e) {
Log.d(CLIENT_TAG, "Unknown Host", e);
} catch (IOException e) {
Log.d(CLIENT_TAG, "I/O Exception", e);
} catch (Exception e) {
Log.d(CLIENT_TAG, "Error3", e);
}
Log.d(CLIENT_TAG, "Client sent message: " + msg);
}
(音频发送)
@Override
public void run() {
audioRecord.startRecording();
byte[] buffer = new byte[recBufSize];
DataOutputStream dataOutputStream = new DataOutputStream(mOutputStream);
if (mOutputStream != null) {
try {
dataOutputStream.writeInt(SOUND_KEY);
dataOutputStream.writeInt(recBufSize);
logD("AUDIO OUT " + buffer.length);
while (isRecording) {
int readSize = audioRecord.read(buffer, 0, recBufSize);
dataOutputStream.writeUTF("#@@#");
dataOutputStream.writeInt(readSize);
dataOutputStream.write(buffer, 0, readSize);
dataOutputStream.flush();
double sum = 0;
for (int i = 0; i < readSize; i++) {
sum += buffer[i] * buffer[i];
}
if (readSize > 0) {
final double amplitude = sum / readSize;
int result = (int) avgQueue(Math.sqrt(amplitude), 10);
if (mSoundControl != null)
mSoundControl.setSoundLevel(result);
logD("AMPLITUDE " + result);
}
}
} catch (Exception e) {
logD(e.getMessage());
}
audioRecord.stop();
}
(数据接收)
DataInputStream is = new DataInputStream(inStream);
while (!Thread.currentThread().isInterrupted()) {
try {
if (is.readUTF().equals("#@@#")) {
token = is.readInt();
dataKey = token;
switch (token) {
case 0:
break;
case CONTROL_KEY:
readControlMessage(is);
break;
case IMAGE_KEY:
readImageMessage(is);
break;
case SOUND_KEY:
readSoundMessage(is);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
请告诉我有什么问题