Created
February 14, 2020 20:16
-
-
Save tir38/31ce950fe6413b81187675d2b32d4025 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mport android.media.AudioFormat | |
import android.media.AudioRecord | |
import android.media.MediaRecorder | |
class AudioRecorder { | |
private val minBufferSize: Int = AudioRecord.getMinBufferSize(SAMPLE_RATE_HZ, AUDIO_RECORDING_FORMAT, AUDIO_ENCODING) | |
private var audioRecord: AudioRecord? = null | |
fun startRecording() { | |
if (audioRecord != null) { | |
throw RuntimeException("Starting record with non null audioRecord, Did you forget to clean something up?") | |
} | |
audioRecord = AudioRecord(MediaRecorder.AudioSource.DEFAULT, | |
SAMPLE_RATE_HZ, | |
AUDIO_RECORDING_FORMAT, | |
AUDIO_ENCODING, | |
minBufferSize) | |
audioRecord?.startRecording() | |
val data = ShortArray(minBufferSize) | |
while (isRecording) { | |
val numberOfShortsRead = audioRecord?.read(data, 0, data.size) ?: AUDIO_RECORD_IS_NULL_ERROR | |
// write to buffer if its safe | |
if (numberOfShortsRead >= 0) { | |
// TODO so something with data | |
} else { | |
// TODO handle error including AUDIO_RECORD_IS_NULL_ERROR | |
} | |
} | |
audioRecord?.release() | |
audioRecord = null // docs say we have to null this after release | |
} | |
fun stopRecording() { | |
if (audioRecord?.state == AudioRecord.STATE_INITIALIZED) { | |
audioRecord?.stop() | |
audioRecord?.release() | |
audioRecord = null // docs say we have to null this after release | |
} | |
} | |
private val isRecording: Boolean | |
get() = audioRecord?.recordingState == AudioRecord.RECORDSTATE_RECORDING | |
companion object { | |
private const val AUDIO_RECORDING_FORMAT = AudioFormat.CHANNEL_IN_MONO | |
private const val SAMPLE_RATE_HZ = 16000 | |
private const val AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT | |
private const val AUDIO_RECORD_IS_NULL_ERROR = -999 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment