blob: 3b70b67673c12c555b4a90865e1eff7ef4a4f2c8 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package coffee.liz.rookery.audio
import javax.sound.sampled.AudioFormat
import javax.sound.sampled.AudioSystem
/** Plays [Chime] PCM on a daemon thread. Silently does nothing if there's no audio device. */
object ChimePlayer {
fun play(notes: List<Chime.Note>) {
val pcm = Chime.render(notes)
Thread {
runCatching {
val format = AudioFormat(Chime.SAMPLE_RATE.toFloat(), 16, 1, true, false)
val bytes = ByteArray(pcm.size * 2)
for (i in pcm.indices) { bytes[2 * i] = pcm[i].toByte(); bytes[2 * i + 1] = (pcm[i].toInt() shr 8).toByte() }
AudioSystem.getSourceDataLine(format).use { line ->
line.open(format); line.start(); line.write(bytes, 0, bytes.size); line.drain()
}
}
}.apply { isDaemon = true; name = "chime" }.start()
}
}
|