martmists
02/03/2024, 2:27 PMval points by produceState(FloatArray(2) { 0f }) {
val format = AudioFormat(44100f, 16, 2, true, true)
val info = DataLine.Info(TargetDataLine::class.java, format)
val line = AudioSystem.getLine(info) as TargetDataLine
line.open(format)
line.start()
while (true) {
val array = ByteArray(1024) // 256 samples/channel/frame
line.read(array, 0, array.size)
val buffer = ByteBuffer.wrap(array)
val floats = FloatArray(array.size / 4) { i ->
val l = buffer.getShort().toFloat()
val r = buffer.getShort().toFloat()
(l + r) * norm / Short.MAX_VALUE.toFloat()
}
value = floats
delay(1) // delay required to not hang the main thread
}
}
However, this lags the application too much. On the other hand, I tried wrapping everything inside produceState in a launch(<http://Dispatchers.IO|Dispatchers.IO>)
but that ended up only updating the scene at ~6fps.
As for displaying, I'm using this snippet:
Canvas(modifier = ...) {
for (i in 0 until points.lastIndex) {
val dx = i.toFloat() / points.size
val dy = points[i]
val x = dx * size.width
val y = size.height / 2 + dy * size.height / 2
val dx2 = (i + 1).toFloat() / points.size
val dy2 = points[i + 1]
val x2 = dx2 * size.width
val y2 = size.height / 2 + dy2 * size.height / 2
drawLine(
color = Color.Green,
start = Offset(x, y),
end = Offset(x2, y2),
strokeWidth = 10f
)
}
}
What can I do to make this display at an acceptable framerate?Chrimaeon
02/03/2024, 2:47 PMread
.
2.
while (isActive) {
value =
withContext(Dispatchers.Default) {
line.read(array, 0, array.size)
val buffer = ByteBuffer.wrap(array)
FloatArray(array.size / 4) { i ->
val l = buffer.getShort().toFloat()
val r = buffer.getShort().toFloat()
(l + r) * norm / Short.MAX_VALUE.toFloat()
}
}
}
3. try to optimize buffer.getShort().toFloat()
lots of boxing and unboxing happening here.
4. I’d make Short.MAX_VALUE.toFloat()
a constant for the same reason.Chrimaeon
02/03/2024, 2:49 PM16.6ms
(time you have at 60 fps)Kirill Grouchnikov
02/03/2024, 3:44 PMmartmists
02/03/2024, 5:03 PMMichael Paus
02/03/2024, 5:09 PMmartmists
02/03/2024, 5:22 PMKirill Grouchnikov
02/05/2024, 5:31 AM