Last active
August 3, 2025 03:56
-
-
Save yandroidUA/a2ecc2e373de2d77c487732f31925c45 to your computer and use it in GitHub Desktop.
iOS AudioRecorder
This file contains hidden or 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
| package com.app.animalcare.client.common.utils.audio | |
| import io.github.aakira.napier.Napier | |
| import kotlinx.cinterop.* | |
| import platform.AVFAudio.* | |
| import platform.CoreAudioTypes.kAudioFormatMPEG4AAC | |
| import platform.Foundation.NSError | |
| import platform.Foundation.NSURL | |
| data class LocalUrl( | |
| val url: NSURL, | |
| ) | |
| @OptIn(ExperimentalForeignApi::class, BetaInteropApi::class) | |
| internal actual class AudioRecorder { | |
| private var recorder: AVAudioRecorder? = null | |
| var delegateProtocol: AVAudioRecorderDelegateProtocol? = null | |
| private inline fun createRecorder(url: NSURL, error: CPointer<ObjCObjectVar<NSError?>>?): AVAudioRecorder { | |
| AVAudioSession.sharedInstance().apply { | |
| setCategory(AVAudioSessionCategoryPlayAndRecord, error) | |
| setActive(true, error) | |
| } | |
| val settings = mapOf<Any?, Any?>( | |
| AVFormatIDKey to kAudioFormatMPEG4AAC.toInt(), | |
| AVSampleRateKey to 12000, | |
| AVNumberOfChannelsKey to 1, | |
| AVEncoderAudioQualityKey to AVAudioQualityHigh | |
| ) | |
| Napier.d { "Url is $url, ${url.path}" } | |
| return url.usePinned { | |
| AVAudioRecorder(it.get(), settings, error) | |
| } | |
| } | |
| actual fun start(url: LocalUrl): Boolean { | |
| if (recorder != null) { | |
| recorder?.stop() | |
| recorder = null | |
| } | |
| return memScoped { | |
| val err = allocPointerTo<ObjCObjectVar<NSError?>>() | |
| createRecorder(url = url.url, error = err.value).also { | |
| val error = err.value?.pointed?.value | |
| if (error == null) { | |
| Napier.i { "Audio recorder successfully initialized" } | |
| it.delegate = delegateProtocol | |
| it.prepareToRecord() | |
| it.record() | |
| recorder = it | |
| } else { | |
| Napier.e { "Error while creating audio recorder: ${error.code}, ${error.description}" } | |
| } | |
| } | |
| return err.value?.pointed?.value == null | |
| } | |
| } | |
| actual fun stop() { | |
| recorder?.stop() | |
| recorder = null | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment