2

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 Answers1

0

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.

vyi
  • 1,078
  • 1
  • 19
  • 46
  • Do you know any alternative method if not using MediaRecorder? – Karson Parami Dec 20 '22 at 10:09
  • If you're after the [`wav` format](https://docs.fileformat.com/audio/wav/) as in **choice of wrapper for your audio data** then you can manually write relevant headers to the `byteArrayOutputStream` or use a java based approach as shown [here](https://stackoverflow.com/a/17731392/1504247). But if you are after the `wav` uncompressed audio data, then MediaRecorder won't help. Also, you can use [`setAudioSamplingRate`](https://developer.android.com/reference/android/media/MediaRecorder#setAudioSamplingRate(int)) to set sampling to 48000Hz. – vyi Dec 20 '22 at 15:21