android record mic to ByteArray and stream to server via socket

437 views Asked by At

I am a beginner for kotlin and android application.

I would like to record voice continously and pass the voice data to server via socket.

I tried the code below but the server ended up receiving data in AMR format only.

val byteArrayOutputStream = ByteArrayOutputStream()

val descriptors = ParcelFileDescriptor.createPipe()
val parcelRead = ParcelFileDescriptor(descriptors[0])
val parcelWrite = ParcelFileDescriptor(descriptors[1])

val inputStream: InputStream = ParcelFileDescriptor.AutoCloseInputStream(parcelRead)

val recorder = MediaRecorder()
recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB)
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
recorder.setOutputFile(parcelWrite.fileDescriptor)
recorder.prepare()

recorder.start()

var read: Int
val data = ByteArray(16384)
while ((inputStream.read(data, 0, data.size).also { read = it } != -1)) {
    byteArrayOutputStream.write(data, 0, read)
}
byteArrayOutputStream.flush()

How can I use byteArrayOutputStream to send audio data in WAV format? Is it possible to modify the sampling rate to 48000 using the above code?

Thank you.

1

There are 1 answers

2
vyi On

The usable formats listed in the MediaRecorder.OutputFormat are:

  1. AAC_ADTS

  2. AMR_NB

  3. AMR_WB

  4. MPEG_2_TS

  5. MPEG_4

  6. OGG

  7. RAW_AMR (Deprecated)

  8. THREE_GPP

  9. WEBM

If you are adamant on using the WAV format, you might have to encode the WAV file using the audio data as mentioned here.