Android: Streaming audio over TCP Sockets

前端 未结 3 1389
小蘑菇
小蘑菇 2021-01-31 10:40

For my app, I need to record audio from MIC on an Android phone, and send it over TCP to the other android phone, where it needs to be played.

I am using AudioReco

3条回答
  •  梦毁少年i
    2021-01-31 10:55

    The problem is lying here:

      bufferRead = recordInstance.read(tempBuffer, 0, bufferSize);
      dataOutputStreamInstance.write(tempBuffer);
    

    You read bufferRead worth of bytes but you attempt to write whole buffer to the output stream.

    To improve the recording process, you may consider following points:

    1. Enable NoiseSuppressor (since API 16)
    2. Enable AcousticEchoCanceler (since API 16)
    3. Increase initial buffersize and should read a chunk of bytes smaller than initial buffersize for smoother audiostream
    4. Switch to UDP. Streaming is UDP job.

    Here is my setup for my previous android app:

    // Calculate minimum buffer size
    int minBufferSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO,
                                                     AudioFormat.ENCODING_PCM_16BIT);
    // Initialize AudioRecord for getting audio from device
    AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100,
                                                AudioFormat.CHANNEL_IN_MONO,
                                                AudioFormat.ENCODING_PCM_16BIT, minBufferSize * 4);
    
    if (API > API 16) {
        if (NoiseSuppressor.isAvailable()) {
            NoiseSuppressor.create(recorder.getAudioSessionId()).setEnabled(true);
        }
        if (AcousticEchoCanceler.isAvailable()) {
            AcousticEchoCanceler.create(recorder.getAudioSessionId()).setEnabled(true);
        }
    }
    
    ....
    
    byte[] tempBuffer = new byte[minBufferSize];
    while (/*isRecording*/) {
          bufferRead = recordInstance.read(tempBuffer, 0, minBufferSize);
          dataOutputStreamInstance.write(tempBuffer, 0, bufferRead);
    }
    

提交回复
热议问题