How to create a js-class instance that is unknown to Kotlin yet


#1

I would like to try Kotlin with a tiny music project. I need to instanciate for instance AudioContext and call methods on it. This and many other web-api classes are unknown to Kotlin. How can I extend the definition?


#2

for testing using dynamic is simplest way

val context:dynamic = js("new AudioContext()") // explicit type definition is not required
context.method()

#3

Thanks. Is there a way to add class definitions that are missing? I need to work with a lot of stuff from the web-audio-api


#4

It is actually quite easy:

kexternal class AudioContext {
val sampleRate: Float
fun createGain(): GainNode
}
external class GainNode {

}

fun main(args: Array<String>) {
    val context = AudioContext()
    println(context.sampleRate)
    val gainNode = context.createGain()
    println(gainNode);
}

#5

Simple example (plays sinus)

external class AudioContext {
    val sampleRate: Float
    val destination: AudioNode
    fun createOscillator(): OscillatorNode
}
external open class AudioNode {
    fun connect(destination: AudioNode, output: Int = definedExternally, input: Int = definedExternally): AudioNode
}
external class OscillatorNode : AudioNode {
    fun start(time: Double = definedExternally)
}
fun main(args: Array<String>) {
    val context = AudioContext()
    println(context.sampleRate)
    val osc = context.createOscillator()
    osc.connect(context.destination)
    osc.start()
}