SelfTitled
SelfTitled

Reputation: 33

Getting very small PCM file from AudioRecord

I am trying to write the audio signal recorded on the phone microphone to PCM file, using Android AudioRecord class. The PCM files I am getting are too small and when I convert them to WAV there is only the click sound(10-20ms). The filesize is roughly couple KB for minute. Please help! Changing the buffer size is not helping.

    val SAMPLE_RATE = 44100
    val AUDIO_SOURCE = MediaRecorder.AudioSource.MIC
    val CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_STEREO
    val AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT
    val BUFFER_SIZE_RECORDING =
        AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT)

fun startRecording(dir: String) {
        isRecordingAudio = true
        if (ActivityCompat.checkSelfPermission(
                fragmentActivitySender,
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        recorder = AudioRecord(
            AUDIO_SOURCE, SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT,
            BUFFER_SIZE_RECORDING
        )
        if (this::recorder.isInitialized) {
            recorder.startRecording()
            recordingThread = thread(true) {
                writeAudioDataToFile(dir)
            }

        }
    }

private fun writeAudioDataToFile(dir: String) {
        val audioBuffer = ByteArray(BUFFER_SIZE_RECORDING)
        val outputStream: FileOutputStream?
        try {
            outputStream = FileOutputStream(dir)
        } catch (e: FileNotFoundException) {
            return
        }
        while (isRecordingAudio) {
            val read = recorder.read(audioBuffer,0, BUFFER_SIZE_RECORDING)
            try {
                outputStream.write(read)
                // clean up file writing operations
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        try {
            outputStream.flush()
            outputStream.close()
        } catch (e: IOException) {
            Log.e(ContentValues.TAG, "exception while closing output stream $e")
            e.printStackTrace()
        }
    }

Upvotes: 0

Views: 78

Answers (1)

Uriel Frankel
Uriel Frankel

Reputation: 14622

First thing: You are flushing the file in the loop, and that is wrong. Move: outputStream.flush() outside of the loop to one line above outputStream.close() read more about it here

Second issue, you need to write the audioBuffer, not the read variable. The read variable is the result of the read method, is it successful or not. The real data is in the read buffer.

Upvotes: 1

Related Questions