Skip to content

Audio Record

class AudioRecordModel(private val context: Application) : AndroidViewModel(context) {
private var recoder: MediaRecorder? = null
var isRecording by mutableStateOf(false)
fun start() {
val currentTime = System.currentTimeMillis().let {
SimpleDateFormat("yyyy-MM-dd_HH:mm:ss", Locale.TAIWAN).format(it)
}
val file =
File(context.getExternalFilesDir(Environment.DIRECTORY_MUSIC), "$currentTime.m4a")
recoder = MediaRecorder(context).apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setOutputFile(file)
prepare()
start()
}
isRecording = true
}
fun stop() {
recoder?.apply {
stop()
release()
}
recoder = null
isRecording = false
}
}