0
我編寫了一個應用程序,通過WiFi連接到Rpi上的網絡套接字,並已成功向客戶端和服務器發送數據(如字符串)。下一步是讓客戶端,我的手機在這種情況下,實時接收和播放從服務器發送的音頻數據。通過Android上的套接字接收實時音頻數據
到目前爲止,我已經聲明瞭套接字和音頻變量。一旦一個按鈕被擊中,異步任務「收聽」就開始了。我知道它可以連接到插座。之後,我試圖打開一個輸入流並將其輸入緩衝區,然後實時播放該緩衝區。
我想我很接近搞清楚,但我認爲我沒有把它說得很對。我在代碼中標記了TODO不確定的區域。
public class MainActivity extends AppCompatActivity {
//audio variables
static final int sampleFreq = 44100;
static final int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
static final int streamType = STREAM_MUSIC;
static final int audioMode = MODE_STREAM;
static final int bufferSize = getMinBufferSize(sampleFreq, channelConfig, audioMode);
//socket variables
public Socket mySocket;
private int SERVERPORT = 33333;
private static final String SERVER_IP = "172.24.1.1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
}
public void onClickListen(View view) {
//call async task
new Listen().execute();
}
private class Listen extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
//get IP and port number
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.d(debugStr, "In initial listen connect");
//create socket
mySocket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (mySocket == null) {
str1 = "Socket became null, listener";
return null;
}
//TODO here is all the new audio stuff
try {
//creates buffer to hold incoming audio data
byte [] audioBuffer = new byte[4096];
//creates input stream readers to read incoming data
BufferedInputStream myBis = new BufferedInputStream(mySocket.getInputStream());
DataInputStream myDis = new DataInputStream(myBis);
Log.d(debugStr, "Input created, listener");
// Read the file into the music array.
int i = 0;
//TODO unsure of while loop condition
while (myDis.read() != -1) {
//since incoming audio is unknown size, use estimated buffer size
audioBuffer[bufferSize-1-i] = myDis.readByte();
i++;
}
//create audio track object
AudioTrack myAudioTrack = new AudioTrack(streamType, sampleFreq, channelConfig, audioEncoding, bufferSize, audioMode);
//TODO write audio data to somewhere?
//TODO should this be in a while loop for live stream?
//TODO will this actually play the audio?
myAudioTrack.write(audioBuffer, 0, bufferSize);
//close input streams
myDis.close();
myBis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
mySocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}
}
}
我不認爲我的while循環的條件是正確的,或者是甚至從輸入流中讀取數據的正確方法。我也認爲audioTrack.write應該在while循環中,如果這實際上使音頻播放。
任何幫助或澄清非常感謝!