我想使用UDP在两个手机发送和接收之间使用音频数据的Wi-Fi IP地址。
但是,语音数据还没有到来 我想知道下面的代码中的问题是什么
package com.example.audio;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.app.Activity;
import android.media.*;
import android.widget.Button;
import java.io.*;
import java.net.*;
class ReadAudio implements Runnable{
public AudioRecord record;
public int bufferSize;
byte [] sendData;
InetAddress addr;
DatagramSocket sendDs;
DatagramPacket sendDp;
public void run(){
sendData = new byte[bufferSize];
bufferSize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
record = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
record.startRecording();
try{
addr = InetAddress.getByName("Wi-Fi ip Number");
sendDs = new DatagramSocket();
while(true){
record.read(sendData, 0, bufferSize);
sendDp = new DatagramPacket(sendData, sendData.length, addr, 18763);
sendDs.send(sendDp);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
class PlayAudio implements Runnable{
public AudioTrack track;
byte [] gdata;
byte [][] getdata;
int bufferSize;
InetAddress addr;
DatagramSocket getDs;
DatagramPacket getDp;
public void run(){
bufferSize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
track = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 8000, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
getdata = new byte[16][bufferSize];
gdata = new byte[bufferSize];
int i,j,k, portNumber;
i = 0;
j = 0;
k = 0;
portNumber = 18763;
try{
addr = InetAddress.getByName("Wi-Fi ip Number");
getDs = new DatagramSocket(portNumber, addr);
while(true){
getDp = new DatagramPacket(gdata, gdata.length);
getDs.receive(getDp);
getdata[i] = getDp.getData();
if(i == 8){
j = i;
}
if(j == 8){
track.write(getdata[k], 0, bufferSize);
track.play();
}
if(++i == 16){
i = 0;
}
if(++k == 16){
k = 0;
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button)findViewById(R.id.button1);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ReadAudio ra = new ReadAudio();
PlayAudio pa = new PlayAudio();
Thread RA = new Thread(ra);
Thread PA = new Thread(pa);
RA.start();
PA.start();
}
});
}
}