Sometimes you have to initialise more than one resource and properly clean everything up.
This is the cleanest option I was able to figure out for Kotlin.
Example of usage:
private val buffers: Array<AudioBuffer>
private val device: AudioDevice
private val context: AudioContext
private val source: AudioSource
private val resourcesToCloseLater: AutoCloseable
init {
resourcesToCloseLater = initializingResources { ->
buffers = Array(BUFFER_COUNT) { AudioBuffer.generate().also(::closeLater) }
device = AudioDevice.openDefaultDevice().also(::closeLater)
context = AudioContext.create(device, intArrayOf(0)).also(::closeLater)
context.makeCurrent()
device.createCapabilities()
source = AudioSource.generate().also(::closeLater)
for (i in 0 until BUFFER_COUNT) {
bufferSamples(ShortArray(0))
}
source.play()
device.detectInternalExceptions()
}
}