TextToSpeechService.desktop.kt
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/tts/TextToSpeechService.desktop.kt
1package eu.friedcutlet.yokan.services.tts23import kotlinx.coroutines.delay4import kotlinx.coroutines.Dispatchers5import kotlinx.coroutines.NonCancellable6import kotlinx.coroutines.withContext7import java.util.concurrent.TimeUnit89actual fun createPlatformTextToSpeechService(): TextToSpeechService = DesktopTextToSpeechService()1011private class DesktopTextToSpeechService : TextToSpeechService {12 @Volatile private var currentProcess: Process? = null13 // Probe once per process instead of forking `which` for every paragraph.14 private val hasSpdSay by lazy { commandExists("spd-say") }15 private val hasEspeak by lazy { commandExists("espeak") }1617 override suspend fun voices(language: String?): List<String> = listOf("System default")1819 override suspend fun speak(20 text: String,21 request: TextToSpeechRequest,22 onProgress: (startOffset: Int, endOffset: Int) -> Unit,23 ) {24 if (text.isBlank()) return25 stop()26 val command = pickCommand(text, request) ?: return27 val process = runCatching { ProcessBuilder(command).inheritIO().start() }.getOrNull() ?: return28 currentProcess = process29 try {30 val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500)31 val wordDelayMillis = (60_000L / wordsPerMinute).coerceAtLeast(40L)32 Regex("\\S+").findAll(text).forEach { word ->33 if (!process.isAlive) return@forEach34 onProgress(word.range.first, word.range.last + 1)35 delay(wordDelayMillis)36 }37 while (process.isAlive) delay(50)38 } finally {39 withContext(NonCancellable) { terminate(process) }40 if (currentProcess === process) currentProcess = null41 }42 }4344 override suspend fun stop() {45 val process = currentProcess ?: return46 terminate(process)47 if (currentProcess === process) currentProcess = null48 }4950 private suspend fun terminate(process: Process) = withContext(Dispatchers.IO) {51 if (process.isAlive) process.destroy()52 if (!process.waitFor(2, TimeUnit.SECONDS)) {53 process.destroyForcibly()54 process.waitFor()55 }56 Unit57 }5859 private fun pickCommand(text: String, request: TextToSpeechRequest): List<String>? {60 val os = System.getProperty("os.name").orEmpty().lowercase()61 val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500)62 return when {63 os.contains("mac") -> buildList {64 add("say")65 request.voice?.takeIf { it.isNotBlank() }?.let {66 add("-v")67 add(it)68 }69 add("-r")70 add(wordsPerMinute.toString())71 add(text)72 }73 os.contains("linux") -> when {74 hasSpdSay -> listOf("spd-say", "-r", ((request.speechRate - 0.5) * 200).toInt().toString(), text)75 hasEspeak -> listOf(76 "espeak",77 "-s",78 wordsPerMinute.toString(),79 "-p",80 (request.pitch * 50.0).toInt().coerceIn(0, 99).toString(),81 text,82 )83 else -> null84 }85 os.contains("win") -> listOf(86 "powershell",87 "-Command",88 "Add-Type -AssemblyName System.Speech;" +89 "\$s=New-Object System.Speech.Synthesis.SpeechSynthesizer;" +90 "\$s.Rate=${((request.speechRate - 0.5) * 10).toInt().coerceIn(-10, 10)};" +91 "\$s.Speak(\"${text.replace("\"", " ")}\")",92 )93 else -> null94 }95 }9697 private fun commandExists(name: String): Boolean = runCatching {98 ProcessBuilder("which", name)99 .redirectErrorStream(true)100 .redirectOutput(ProcessBuilder.Redirect.DISCARD)101 .start()102 .waitFor() == 0103 }.getOrDefault(false)104}105