//manifest.xml
//녹음 권한 매니페스트 요청
<uses-permission android:name="android.permission.RECORD_AUDIO" />
private val recoredLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
} else {
}
}
recoredLauncher.launch(Manifest.permission.RECORD_AUDIO)
private var recorder: MediaRecorder? = null
private var isRecording = false
private var job: Job? = null
private var filePath = ""
private fun startRecord() {
recorder = MediaRecorder()
val basePath = requireContext().getExternalFilesDir(null)?.absolutePath
recorder?.apply {
setAudioSource(AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
filePath = "${basePath}/myRecord.3gp"
setOutputFile(filePath)
}
try {
recorder?.prepare()
} catch (e: IOException) {
Log.e(LOG_TAG, "prepare() failed")
return
}
recorder?.start()
getDb()
}
private fun getDb() {
recorder?.let {
isRecording = true
job = CoroutineScope(Dispatchers.Default).launch {
while (isRecording) {
delay(3000L)
val amplitude = it.maxAmplitude
val db = 20 * kotlin.math.log10(amplitude.toDouble())
if (amplitude > 0) {
}
}
}
}
}
override fun onStop() {
super.onStop()
isRecording = false
job?.cancel()
if (recorder != null) {
recorder?.stop()
recorder?.release()
recorder = null
}
}
공식문서