Skip to content

Instantly share code, notes, and snippets.

@yandroidUA
Last active August 3, 2025 03:56
Show Gist options
  • Select an option

  • Save yandroidUA/a2ecc2e373de2d77c487732f31925c45 to your computer and use it in GitHub Desktop.

Select an option

Save yandroidUA/a2ecc2e373de2d77c487732f31925c45 to your computer and use it in GitHub Desktop.
iOS AudioRecorder
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