An audio app on Android and iOS means two APIs. On Android, Oboe or OpenSL ES. On iOS, AVAudioEngine and Core Audio. Two codebases, two sets of bugs, and real-time effects to keep in parity on both.
I built Klarinet for that.
Why “Klarinet”?
Google’s low-latency audio library for Android is called Oboe. A clarinet is in the same family of wind instruments, so the connection felt natural. And since this is a Kotlin library, the K was a no-brainer. Oboe, Clarinet, Kotlin… Klarinet.
What is Klarinet?
Klarinet is an open-source Kotlin Multiplatform (KMP) audio library that gives you a single, idiomatic Kotlin API for low-latency audio playback, recording, file I/O, and real-time effects processing across Android and Apple platforms.
You write your audio code once in Kotlin. Under the hood, Klarinet delegates to Google Oboe (AAudio/OpenSL ES) on Android and AVAudioEngine on Apple.
The library is available on Maven Central right now:
kotlin
implementation("com.vectencia.klarinet:klarinet:0.0.1")
Klarinet 0.6.0 keeps that API and moves the shared DSP core to Rust.
The Problem Klarinet Solves
Compose Multiplatform shares screens, navigation, and business logic across Android and iOS. There is no shared audio layer in KMP. If your app needs to play a tone, record from a mic, decode an MP3, or apply a reverb, you write platform-specific code twice, and you keep both implementations in sync as features change.
Klarinet is that shared audio layer.
What You Can Build With It
Music production apps. DAWs, beat-makers, and loop stations. Klarinet’s effect chain supports 16 built-in effects (reverb, delay, compressor, EQ, chorus, and more), all powered by a shared C++ DSP core. Effects are hot-swappable, so you can add, remove, and reorder them while audio is streaming.
Voice and communication tools. Chat apps, podcast recorders, walkie-talkies. The noise gate, compressor, and parametric EQ run natively in the audio callback, which is what real-time voice processing needs.
Games. Procedural audio, dynamic sound effects, spatial mixing. The callback API gives you direct access to the audio buffer in the low-latency performance mode.
Audio analysis. Spectrum analysers, guitar tuners, and audio visualisers. The levelFlow() API provides real-time metering at 20+ updates per second via Kotlin Flows, and raw PCM access through the callback lets you run FFT, pitch detection, or whatever signal processing you need.
Accessibility tools. Hearing aids, sound amplifiers, frequency boosters. The real-time effects chain can handle parametric EQ, dynamic range compression, and gain adjustments with sub-10ms latency for live audio passthrough.
How It Works
A minimal example that generates a 440Hz sine wave:
kotlin
val engine = AudioEngine.create()
val callback = object : AudioStreamCallback {
private var phase = 0.0
override fun onAudioReady(buffer: FloatArray, numFrames: Int): Int {
for (i in 0 until numFrames) {
buffer[i] = sin(2.0 * Math.PI * 440.0 * phase / 48000.0).toFloat()
phase += 1.0
}
return numFrames
}
}
val stream = engine.openStream(
config = AudioStreamConfig(
sampleRate = 48000,
channelCount = 1,
direction = StreamDirection.OUTPUT,
performanceMode = PerformanceMode.LOW_LATENCY,
),
callback = callback,
)
stream.start()
Same code runs on Android and iOS. The AudioEngine creates a native Oboe stream on Android and an AVAudioEngine node on Apple. Your callback runs directly in the native audio thread.
Recording uses the same shape. Swap StreamDirection.OUTPUT for StreamDirection.INPUT and call stream.read() instead.
The Effects Chain
The library ships with 16 built-in audio effects, all implemented in a shared C++ DSP core that compiles for every target platform:
-
Basic: Gain, Pan, Mute/Solo
-
Dynamics: Compressor, Limiter, Noise Gate
-
EQ/Filters: 8-band Parametric EQ, Low-Pass, High-Pass, Band-Pass
-
Time-based: Delay, Reverb (Freeverb algorithm)
-
Modulation: Chorus, Flanger, Phaser, Tremolo
Effects are created through the engine, chained together, and attached to a stream:
kotlin
val reverb = engine.createEffect(AudioEffectType.REVERB)
reverb.setParameter(ReverbParams.ROOM_SIZE, 0.7f)
val compressor = engine.createEffect(AudioEffectType.COMPRESSOR)
compressor.setParameter(CompressorParams.THRESHOLD, -20f)
val chain = engine.createEffectChain()
chain.add(compressor)
chain.add(reverb)
stream.effectChain = chain
All parameter updates are lock-free and audio-thread safe. You can tweak the reverb wetness or compressor ratio in your UI thread while the audio is playing, with no glitches or dropouts. And the chain itself is hot-swappable: add, remove, or reorder effects in real time.
Because the DSP runs in C++, there’s zero JNI overhead on Android and zero Kotlin/Native interop overhead on Apple. The effects process directly inside the native audio callback. That C++ core is a choice I made for the callback. I explain when I reach for native code in when and why to use C++ on Android.
File I/O
Klarinet handles audio file decoding and encoding out of the box. WAV, MP3, AAC, and M4A are all supported.
kotlin
// Read metadata
val reader = AudioFileReader("/path/to/song.mp3")
val info = reader.info
println("${info.tags.title} by ${info.tags.artist} - ${info.durationMs}ms")
// Decode to PCM
val samples = reader.readAll()
// Or stream in chunks
reader.asFlow(chunkSize = 4096).collect { chunk ->
// Process each chunk without loading the entire file into memory
}
There are also convenience methods for common operations:
kotlin
// One-liner playback
val stream = engine.playFile("/path/to/song.mp3")
stream.start()
// One-liner recording
val stream = engine.recordToFile("/path/to/recording.wav", AudioFileFormat.WAV)
stream.start()
Coroutines Support
The core klarinet module has zero dependency on coroutines, keeping it lightweight. But if you’re already using coroutines (and you probably are), the optional klarinet-coroutines module adds Flow-based APIs and suspending functions:
kotlin
implementation("com.vectencia.klarinet:klarinet-coroutines:0.0.1")
This gives you reactive stream state observation, real-time level metering as a Flow, async file I/O on Dispatchers.IO, and streaming file decoding via asFlow().
SwiftUI Ready
If your iOS team prefers native SwiftUI over Compose Multiplatform, Klarinet works there too. The library exports a Kotlin/Native framework that Swift can import directly:
swift
import Klarinet
let engine = AudioEngine.companion.create()
let stream = engine.openStream(config: config, callback: callback)
stream.start()
The repo includes a full SwiftUI demo app with five screens (tone generator, mic meter, latency benchmark, file player, effects chain) built with pure SwiftUI and MVVM architecture.
Architecture
Klarinet is structured as a single KMP module with expect/actual declarations:
-
commonMain contains the entire public API surface:
AudioEngine,AudioStream, effects, file I/O, and all data types. -
androidMain implements everything via Google Oboe with C++17/JNI.
-
appleMain implements everything via AVAudioEngine, shared across iOS, macOS, and tvOS.
-
cpp/dsp is the shared C++ DSP library that compiles for all platforms. It contains the effect implementations, DSP primitives (biquad filters, LFOs, envelope followers, circular buffers), a lock-free effect chain, and SPSC ring buffers.
The language breakdown is 52.8% C++, 37.7% Kotlin, 7.1% Swift. The performance-critical audio processing lives in C++, the API and platform integration is in Kotlin, and the native iOS demo is in Swift.
Getting Started
Add the dependency to your KMP project:
kotlin
kotlin {
sourceSets {
commonMain.dependencies {
implementation("com.vectencia.klarinet:klarinet:0.0.1")
implementation("com.vectencia.klarinet:klarinet-coroutines:0.0.1") // optional
}
}
}
Check out the demo apps in the repository for working examples of every feature. The Compose Multiplatform demo runs on both Android and iOS, and the SwiftUI demo shows native integration patterns.
The project is Apache 2.0 licensed and open for contributions. Head over to the GitHub repo to star it, try it out, or open an issue.
What’s Next
This is version 0.0.1, the first public release. It has low-latency I/O, a full effects chain, file decoding and encoding, and coroutines support.
I’m planning to expand platform support, add more effects, improve the file format coverage, and build out more documentation. If you’re working on an audio app with KMP and have specific needs, I’d love to hear about them.
You can find me on LinkedIn, Medium, and YouTube. And if Klarinet saves you from writing platform-specific audio code twice, drop a star on the repo.
I (David Cruz Anaya) am a senior mobile engineer (davthecoder). I build tools and educational content for the Android and KMP developer community, and write more over at davthecoder.com.
Una app de audio en Android y en iOS son dos APIs. En Android, Oboe u OpenSL ES. En iOS, AVAudioEngine y Core Audio. Dos codebases, el doble de bugs, y efectos en tiempo real que hay que mantener en paridad en las dos.
Construí Klarinet para eso.
¿Por qué «Klarinet»?
La biblioteca de audio de baja latencia de Google para Android se llama Oboe. Un clarinete pertenece a la misma familia de instrumentos de viento, así que la conexión salió sola. Y, como esto es una biblioteca de Kotlin, la K caía por su peso. Oboe, clarinete, Kotlin… Klarinet.
¿Qué es Klarinet?
Klarinet es una biblioteca de audio de código abierto para Kotlin Multiplatform (KMP) que te da una única API de Kotlin, idiomática, para reproducción de audio de baja latencia, grabación, entrada y salida de ficheros y procesamiento de efectos en tiempo real, en Android y en las plataformas de Apple.
Escribes el código de audio una sola vez, en Kotlin. Por debajo, Klarinet delega en Google Oboe (AAudio/OpenSL ES) en Android y en AVAudioEngine en Apple.
La biblioteca ya está disponible en Maven Central:
kotlin
implementation("com.vectencia.klarinet:klarinet:0.0.1")
Klarinet 0.6.0 mantiene esa API y pasa el núcleo DSP compartido a Rust.
El problema que resuelve Klarinet
Compose Multiplatform comparte pantallas, navegación y lógica de negocio entre Android e iOS. No hay una capa de audio compartida en KMP. Si tu app necesita reproducir un tono, grabar desde un micrófono, descodificar un MP3 o aplicar una reverberación, escribes código específico de cada plataforma dos veces, y mantienes las dos implementaciones sincronizadas a medida que cambian las funciones.
Klarinet es esa capa de audio compartida.
Qué puedes construir con él
Apps de producción musical. DAW, creadores de ritmos y estaciones de bucles. La cadena de efectos de Klarinet admite 16 efectos integrados (reverb, delay, compresor, EQ, chorus y más), todos impulsados por un núcleo DSP de C++ compartido. Los efectos se intercambian en caliente, así que puedes añadirlos, quitarlos y reordenarlos mientras el audio está en streaming.
Herramientas de voz y comunicación. Apps de chat, grabadoras de pódcast, walkie-talkies. La puerta de ruido, el compresor y la EQ paramétrica corren de forma nativa en el callback de audio, que es lo que necesita el procesado de voz en tiempo real.
Juegos. Audio procedural, efectos de sonido dinámicos, mezcla espacial. La API de callback te da acceso directo al búfer de audio en el modo de rendimiento de baja latencia.
Análisis de audio. Analizadores de espectro, afinadores de guitarra y visualizadores de audio. La API levelFlow() ofrece medición en tiempo real, a más de 20 actualizaciones por segundo, mediante Kotlin Flows, y el acceso al PCM crudo a través del callback te deja ejecutar FFT, detección de tono o el procesamiento de señal que necesites.
Herramientas de accesibilidad. Audífonos, amplificadores de sonido, reforzadores de frecuencia. La cadena de efectos en tiempo real puede encargarse de la EQ paramétrica, la compresión del rango dinámico y los ajustes de ganancia con una latencia por debajo de 10 ms para el paso de audio en directo.
Cómo funciona
Un ejemplo mínimo que genera una onda sinusoidal de 440 Hz:
kotlin
val engine = AudioEngine.create()
val callback = object : AudioStreamCallback {
private var phase = 0.0
override fun onAudioReady(buffer: FloatArray, numFrames: Int): Int {
for (i in 0 until numFrames) {
buffer[i] = sin(2.0 * Math.PI * 440.0 * phase / 48000.0).toFloat()
phase += 1.0
}
return numFrames
}
}
val stream = engine.openStream(
config = AudioStreamConfig(
sampleRate = 48000,
channelCount = 1,
direction = StreamDirection.OUTPUT,
performanceMode = PerformanceMode.LOW_LATENCY,
),
callback = callback,
)
stream.start()
El mismo código se ejecuta en Android y en iOS. AudioEngine crea un stream nativo de Oboe en Android y un nodo de AVAudioEngine en Apple. Tu callback se ejecuta directamente en el hilo de audio nativo.
Grabar usa la misma forma. Cambia StreamDirection.OUTPUT por StreamDirection.INPUT y llama a stream.read() en su lugar.
La cadena de efectos
La biblioteca trae 16 efectos de audio integrados, todos implementados en un núcleo DSP de C++ compartido que compila para cada plataforma de destino:
-
Básicos: Gain, Pan, Mute/Solo
-
Dinámica: Compressor, Limiter, Noise Gate
-
EQ y filtros: EQ paramétrica de 8 bandas, paso bajo, paso alto, paso banda
-
Basados en el tiempo: Delay, Reverb (algoritmo Freeverb)
-
Modulación: Chorus, Flanger, Phaser, Tremolo
Los efectos se crean a través del motor, se encadenan y se acoplan a un stream:
kotlin
val reverb = engine.createEffect(AudioEffectType.REVERB)
reverb.setParameter(ReverbParams.ROOM_SIZE, 0.7f)
val compressor = engine.createEffect(AudioEffectType.COMPRESSOR)
compressor.setParameter(CompressorParams.THRESHOLD, -20f)
val chain = engine.createEffectChain()
chain.add(compressor)
chain.add(reverb)
stream.effectChain = chain
Todas las actualizaciones de parámetros van sin bloqueos y son seguras para el hilo de audio. Puedes retocar el nivel wet de la reverb o la relación del compresor en el hilo de la interfaz mientras el audio suena, sin chasquidos ni cortes. Y la cadena en sí se intercambia en caliente: añade, quita o reordena efectos en tiempo real.
Como el DSP corre en C++, no hay sobrecarga de JNI en Android ni sobrecarga de interoperabilidad Kotlin/Native en Apple. Los efectos se procesan directamente dentro del callback de audio nativo. Ese núcleo de C++ es una elección que tomé para el callback. Explico cuándo echo mano del código nativo en cuándo y por qué usar C++ en Android.
Entrada y salida de ficheros
Klarinet se encarga de la descodificación y la codificación de ficheros de audio de serie. WAV, MP3, AAC y M4A están soportados.
kotlin
// Read metadata
val reader = AudioFileReader("/path/to/song.mp3")
val info = reader.info
println("${info.tags.title} by ${info.tags.artist} - ${info.durationMs}ms")
// Decode to PCM
val samples = reader.readAll()
// Or stream in chunks
reader.asFlow(chunkSize = 4096).collect { chunk ->
// Process each chunk without loading the entire file into memory
}
También hay métodos de conveniencia para operaciones habituales:
kotlin
// One-liner playback
val stream = engine.playFile("/path/to/song.mp3")
stream.start()
// One-liner recording
val stream = engine.recordToFile("/path/to/recording.wav", AudioFileFormat.WAV)
stream.start()
Soporte de corrutinas
El módulo central klarinet no depende en absoluto de las corrutinas, así que se mantiene ligero. Pero si ya usas corrutinas (y es probable que sí), el módulo opcional klarinet-coroutines añade APIs basadas en Flow y funciones de suspensión:
kotlin
implementation("com.vectencia.klarinet:klarinet-coroutines:0.0.1")
Con esto tienes observación reactiva del estado del stream, medición de nivel en tiempo real como un Flow, entrada y salida de ficheros asíncrona en Dispatchers.IO, y descodificación de ficheros en streaming mediante asFlow().
Listo para SwiftUI
Si tu equipo de iOS prefiere SwiftUI nativo frente a Compose Multiplatform, Klarinet también funciona ahí. La biblioteca exporta un framework de Kotlin/Native que Swift puede importar directamente:
swift
import Klarinet
let engine = AudioEngine.companion.create()
let stream = engine.openStream(config: config, callback: callback)
stream.start()
El repositorio incluye una app de demostración completa en SwiftUI, con cinco pantallas (generador de tonos, medidor de micrófono, banco de pruebas de latencia, reproductor de ficheros y cadena de efectos), hecha con SwiftUI puro y arquitectura MVVM.
Arquitectura
Klarinet está estructurado como un único módulo de KMP, con declaraciones expect/actual:
-
commonMain contiene toda la superficie de API pública:
AudioEngine,AudioStream, efectos, entrada y salida de ficheros, y todos los tipos de datos. -
androidMain lo implementa todo mediante Google Oboe, con C++17/JNI.
-
appleMain lo implementa todo mediante AVAudioEngine, compartido entre iOS, macOS y tvOS.
-
cpp/dsp es la biblioteca DSP de C++ compartida, que compila para todas las plataformas. Contiene las implementaciones de los efectos, primitivas de DSP (filtros biquad, LFO, seguidores de envolvente, búferes circulares), una cadena de efectos sin bloqueos y búferes de anillo SPSC.
El reparto por lenguajes es 52,8 % C++, 37,7 % Kotlin, 7,1 % Swift. El procesamiento de audio crítico para el rendimiento vive en C++, la API y la integración con la plataforma están en Kotlin, y la demo nativa de iOS está en Swift.
Primeros pasos
Añade la dependencia a tu proyecto de KMP:
kotlin
kotlin {
sourceSets {
commonMain.dependencies {
implementation("com.vectencia.klarinet:klarinet:0.0.1")
implementation("com.vectencia.klarinet:klarinet-coroutines:0.0.1") // optional
}
}
}
Échale un ojo a las apps de demostración del repositorio: hay ejemplos que funcionan de cada función. La demo de Compose Multiplatform corre en Android y en iOS, y la demo de SwiftUI muestra patrones de integración nativa.
El proyecto tiene licencia Apache 2.0 y está abierto a contribuciones. Pásate por el repositorio de GitHub para darle una estrella, probarlo o abrir una incidencia.
Qué viene ahora
Esta es la versión 0.0.1, la primera publicación pública. Tiene E/S de baja latencia, una cadena de efectos completa, descodificación y codificación de ficheros, y soporte de corrutinas.
Tengo previsto ampliar el soporte de plataformas, añadir más efectos, mejorar la cobertura de formatos de fichero y redactar una documentación más completa. Si estás haciendo una app de audio con KMP y tienes necesidades concretas, me encantaría conocerlas.
Puedes encontrarme en LinkedIn, Medium y YouTube. Y si Klarinet te ahorra escribir dos veces código de audio específico de cada plataforma, deja una estrella en el repositorio.
Yo (David Cruz Anaya) soy ingeniero sénior de desarrollo móvil (davthecoder). Construyo herramientas y contenido formativo para la comunidad de desarrollo de Android y KMP, y escribo más en davthecoder.com.
แอปเสียงบน Android และ iOS หมายถึงสอง API บน Android คือ Oboe หรือ OpenSL ES บน iOS คือ AVAudioEngine และ Core Audio สองโค้ดเบส สองชุดบั๊ก และเอฟเฟกต์เรียลไทม์ที่ต้องรักษาให้เสมอกันทั้งสองฝั่ง
ผมสร้าง Klarinet เพื่อเรื่องนั้น
ทำไมชื่อ “Klarinet”
ไลบรารีเสียงความหน่วงต่ำของ Google สำหรับ Android ชื่อ Oboe คลาริเน็ตอยู่ในตระกูลเครื่องเป่าเดียวกัน ดังนั้นความเชื่อมจึงเป็นธรรมชาติ และเพราะนี่เป็นไลบรารี Kotlin ตัว K จึงไม่ต้องคิด Oboe, Clarinet, Kotlin… Klarinet
Klarinet คืออะไร
Klarinet เป็นไลบรารีเสียง Kotlin Multiplatform (KMP) แบบโอเพนซอร์ส ที่ให้ API Kotlin ที่เป็นสำนวนเดียว สำหรับการเล่นเสียงความหน่วงต่ำ การอัด ไฟล์ I/O และการประมวลผลเอฟเฟกต์เรียลไทม์ ข้าม Android และแพลตฟอร์ม Apple
คุณเขียนโค้ดเสียงครั้งเดียวใน Kotlin ใต้ฝากระโปรง Klarinet ส่งงานให้ Google Oboe (AAudio/OpenSL ES) บน Android และ AVAudioEngine บน Apple
ไลบรารีอยู่บน Maven Central ตอนนี้:
kotlin
implementation("com.vectencia.klarinet:klarinet:0.0.1")
Klarinet 0.6.0 คง API นั้น และย้ายคอร์ DSP ที่ใช้ร่วมกันไปที่ Rust
ปัญหาที่ Klarinet แก้
Compose Multiplatform แชร์หน้าจอ การนำทาง และลอจิกธุรกิจข้าม Android และ iOS ใน KMP ไม่มีชั้นเสียงที่ใช้ร่วมกัน ถ้าแอปของคุณต้องเล่นโทน อัดจากไมค์ ถอดรหัส MP3 หรือใส่รีเวิร์บ คุณเขียนโค้ดเฉพาะแพลตฟอร์มสองครั้ง และคุณรักษาทั้งสองอิมพลีเมนต์ให้ตรงกันเมื่อฟีเจอร์เปลี่ยน
Klarinet คือชั้นเสียงที่ใช้ร่วมกันนั้น
สิ่งที่คุณสร้างด้วยมันได้
แอปผลิตเพลง DAW, เครื่องทำบีต และลูปสเตชัน เชนเอฟเฟกต์ของ Klarinet รองรับเอฟเฟกต์ในตัว 16 ตัว (รีเวิร์บ ดีเลย์ คอมเพรสเซอร์ EQ คอรัส และอื่น ๆ) ทั้งหมดขับด้วยคอร์ DSP C++ ที่ใช้ร่วมกัน เอฟเฟกต์สลับขณะร้อนได้ ดังนั้นคุณเพิ่ม เอาออก และเรียงใหม่ได้ขณะเสียงกำลังสตรีม
เครื่องมือเสียงและการสื่อสาร แอปแชท เครื่องอัดพอดแคสต์ วิทยุสื่อสาร นอยส์เกต คอมเพรสเซอร์ และ EQ พาราเมตริก รันแบบเนทีฟใน callback เสียง ซึ่งเป็นสิ่งที่การประมวลผลเสียงเรียลไทม์ต้องการ
เกม เสียงเชิงกระบวน เอฟเฟกต์เสียงไดนามิก การมิกซ์เชิงพื้นที่ API callback ให้คุณเข้าถึงบัฟเฟอร์เสียงตรง ในโหมดประสิทธิภาพความหน่วงต่ำ
การวิเคราะห์เสียง เครื่องวิเคราะห์สเปกตรัม เครื่องตั้งเสียงกีตาร์ และวิชวลไลเซอร์เสียง API levelFlow() ให้การวัดระดับเรียลไทม์ที่ 20 ครั้งขึ้นไปต่อวินาทีผ่าน Kotlin Flow และการเข้าถึง PCM ดิบผ่าน callback ให้คุณรัน FFT ตรวจพิทช์ หรือการประมวลผลสัญญาณอะไรก็ได้ที่คุณต้องการ
เครื่องมือการเข้าถึง เครื่องช่วยฟัง เครื่องขยายเสียง เครื่องดันความถี่ เชนเอฟเฟกต์เรียลไทม์รับ EQ พาราเมตริก การบีบไดนามิกเรนจ์ และการปรับเกน ด้วยความหน่วงต่ำกว่า 10 ms สำหรับการผ่านเสียงสด
มันทำงานอย่างไร
ตัวอย่างเล็กที่สร้างคลื่นไซน์ 440 Hz:
kotlin
val engine = AudioEngine.create()
val callback = object : AudioStreamCallback {
private var phase = 0.0
override fun onAudioReady(buffer: FloatArray, numFrames: Int): Int {
for (i in 0 until numFrames) {
buffer[i] = sin(2.0 * Math.PI * 440.0 * phase / 48000.0).toFloat()
phase += 1.0
}
return numFrames
}
}
val stream = engine.openStream(
config = AudioStreamConfig(
sampleRate = 48000,
channelCount = 1,
direction = StreamDirection.OUTPUT,
performanceMode = PerformanceMode.LOW_LATENCY,
),
callback = callback,
)
stream.start()
โค้ดเดียวกันรันบน Android และ iOS AudioEngine สร้างสตรีม Oboe เนทีฟบน Android และโหนด AVAudioEngine บน Apple callback ของคุณรันตรงในเธรดเสียงเนทีฟ
การอัดใช้รูปเดียวกัน สลับ StreamDirection.OUTPUT เป็น StreamDirection.INPUT แล้วเรียก stream.read() แทน
เชนเอฟเฟกต์
ไลบรารีมาพร้อมเอฟเฟกต์เสียงในตัว 16 ตัว ทั้งหมดอิมพลีเมนต์ในคอร์ DSP C++ ที่ใช้ร่วมกัน ซึ่งคอมไพล์ได้ทุกแพลตฟอร์มเป้าหมาย:
-
พื้นฐาน: Gain, Pan, Mute/Solo
-
ไดนามิก: Compressor, Limiter, Noise Gate
-
EQ/ฟิลเตอร์: Parametric EQ 8 แบนด์, Low-Pass, High-Pass, Band-Pass
-
ตามเวลา: Delay, Reverb (อัลกอริทึม Freeverb)
-
มอดูเลชัน: Chorus, Flanger, Phaser, Tremolo
เอฟเฟกต์ถูกสร้างผ่านเอนจิน โซ่เข้าด้วยกัน แล้วติดกับสตรีม:
kotlin
val reverb = engine.createEffect(AudioEffectType.REVERB)
reverb.setParameter(ReverbParams.ROOM_SIZE, 0.7f)
val compressor = engine.createEffect(AudioEffectType.COMPRESSOR)
compressor.setParameter(CompressorParams.THRESHOLD, -20f)
val chain = engine.createEffectChain()
chain.add(compressor)
chain.add(reverb)
stream.effectChain = chain
การอัปเดตพารามิเตอร์ทั้งหมดไม่มีล็อก และปลอดภัยบนเธรดเสียง คุณปรับความเปียกของรีเวิร์บหรืออัตราส่วนคอมเพรสเซอร์ในเธรด UI ได้ขณะเสียงกำลังเล่น โดยไม่มีกลิตช์หรือเสียงขาด และตัวเชนเองสลับขณะร้อนได้: เพิ่ม เอาออก หรือเรียงเอฟเฟกต์ใหม่แบบเรียลไทม์
เพราะ DSP รันใน C++ จึงไม่มีโอเวอร์เฮด JNI บน Android และไม่มีโอเวอร์เฮด interop ของ Kotlin/Native บน Apple เอฟเฟกต์ประมวลผลตรงใน callback เสียงเนทีฟ คอร์ C++ นั้นเป็นทางเลือกที่ผมทำสำหรับ callback ผมอธิบายว่าเมื่อไรผมเอื้อมไปหาโค้ดเนทีฟใน เมื่อไรและทำไมถึงใช้ C++ บน Android
ไฟล์ I/O
Klarinet จัดการการถอดรหัสและเข้ารหัสไฟล์เสียงมาให้เลย WAV, MP3, AAC และ M4A รองรับทั้งหมด
kotlin
// Read metadata
val reader = AudioFileReader("/path/to/song.mp3")
val info = reader.info
println("${info.tags.title} by ${info.tags.artist} - ${info.durationMs}ms")
// Decode to PCM
val samples = reader.readAll()
// Or stream in chunks
reader.asFlow(chunkSize = 4096).collect { chunk ->
// Process each chunk without loading the entire file into memory
}
ยังมีเมธอดสะดวกสำหรับการทำงานทั่วไป:
kotlin
// One-liner playback
val stream = engine.playFile("/path/to/song.mp3")
stream.start()
// One-liner recording
val stream = engine.recordToFile("/path/to/recording.wav", AudioFileFormat.WAV)
stream.start()
รองรับคอรูทีน
โมดูล klarinet แกนไม่พึ่งคอรูทีนเลย เพื่อให้มันเบา แต่ถ้าคุณใช้คอรูทีนอยู่แล้ว (และคุณน่าจะใช้) โมดูลทางเลือก klarinet-coroutines เพิ่ม API แบบ Flow และฟังก์ชัน suspending:
kotlin
implementation("com.vectencia.klarinet:klarinet-coroutines:0.0.1")
สิ่งนี้ให้คุณการสังเกตสถานะสตรีมแบบรีแอคทีฟ การวัดระดับเรียลไทม์เป็น Flow, ไฟล์ I/O แบบ async บน Dispatchers.IO และการถอดรหัสไฟล์แบบสตรีมผ่าน asFlow()
พร้อมสำหรับ SwiftUI
ถ้าทีม iOS ของคุณชอบ SwiftUI เนทีฟมากกว่า Compose Multiplatform Klarinet ใช้ที่นั่นได้ด้วย ไลบรารีส่งออกเฟรมเวิร์ก Kotlin/Native ที่ Swift อิมพอร์ตตรงได้:
swift
import Klarinet
let engine = AudioEngine.companion.create()
let stream = engine.openStream(config: config, callback: callback)
stream.start()
รีโปมีแอปเดโม SwiftUI เต็มห้าหน้าจอ (ตัวสร้างโทน มิเตอร์ไมค์ เบนช์มาร์กความหน่วง ตัวเล่นไฟล์ เชนเอฟเฟกต์) สร้างด้วย SwiftUI ล้วนและสถาปัตยกรรม MVVM
สถาปัตยกรรม
Klarinet จัดเป็นโมดูล KMP เดียวด้วยการประกาศ expect/actual:
-
commonMain มีผิว API สาธารณะทั้งหมด:
AudioEngine,AudioStream, เอฟเฟกต์, ไฟล์ I/O และชนิดข้อมูลทั้งหมด -
androidMain อิมพลีเมนต์ทุกอย่างผ่าน Google Oboe ด้วย C++17/JNI
-
appleMain อิมพลีเมนต์ทุกอย่างผ่าน AVAudioEngine ใช้ร่วมกันข้าม iOS, macOS และ tvOS
-
cpp/dsp คือไลบรารี DSP C++ ที่ใช้ร่วมกัน ซึ่งคอมไพล์ได้ทุกแพลตฟอร์ม มันมีอิมพลีเมนต์เอฟเฟกต์ พริมิทีฟ DSP (ฟิลเตอร์ biquad, LFO, envelope follower, บัฟเฟอร์วงกลม) เชนเอฟเฟกต์แบบไม่มีล็อก และริงบัฟเฟอร์ SPSC
สัดส่วนภาษาคือ C++ 52.8%, Kotlin 37.7%, Swift 7.1% การประมวลผลเสียงที่ประสิทธิภาพสำคัญอยู่ใน C++ API และการเชื่อมแพลตฟอร์มอยู่ใน Kotlin และเดโม iOS เนทีฟอยู่ใน Swift
เริ่มต้น
เพิ่มดีเพนเดนซีเข้าโปรเจกต์ KMP ของคุณ:
kotlin
kotlin {
sourceSets {
commonMain.dependencies {
implementation("com.vectencia.klarinet:klarinet:0.0.1")
implementation("com.vectencia.klarinet:klarinet-coroutines:0.0.1") // optional
}
}
}
ดูแอปเดโมในรีโปสำหรับตัวอย่างที่รันได้ของทุกฟีเจอร์ เดโม Compose Multiplatform รันทั้งบน Android และ iOS และเดโม SwiftUI แสดงแพตเทิร์นการเชื่อมเนทีฟ
โปรเจกต์ใช้สัญญาอนุญาต Apache 2.0 และเปิดรับการมีส่วนร่วม ไปที่ รีโป GitHub เพื่อกดดาว ลองใช้ หรือเปิด issue
อะไรต่อไป
นี่คือเวอร์ชัน 0.0.1 รีลีสสาธารณะครั้งแรก มันมี I/O ความหน่วงต่ำ เชนเอฟเฟกต์เต็ม การถอดรหัสและเข้ารหัสไฟล์ และรองรับคอรูทีน
ผมวางแผนขยายการรองรับแพลตฟอร์ม เพิ่มเอฟเฟกต์ ปรับปรุงความครอบคลุมฟอร์แมตไฟล์ และเขียนเอกสารเพิ่ม ถ้าคุณกำลังทำแอปเสียงด้วย KMP และมีความต้องการเฉพาะ ผมอยากฟัง
คุณหาผมได้ที่ LinkedIn, Medium และ YouTube และถ้า Klarinet ช่วยคุณไม่ต้องเขียนโค้ดเสียงเฉพาะแพลตฟอร์มสองครั้ง กดดาวที่รีโป
ผม (David Cruz Anaya) เป็นวิศวกรมือถืออาวุโส (davthecoder) ผมสร้างเครื่องมือและเนื้อหาการเรียนรู้สำหรับชุมชนนักพัฒนา Android และ KMP และเขียนเพิ่มที่ davthecoder.com.

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…