package eu.friedcutlet.yokan.services.tts import kotlinx.coroutines.delay import platform.AVFAudio.AVSpeechBoundary import platform.AVFAudio.AVSpeechSynthesisVoice import platform.AVFAudio.AVSpeechSynthesizer import platform.AVFAudio.AVSpeechUtterance actual fun createPlatformTextToSpeechService(): TextToSpeechService = IosTextToSpeechService() private class IosTextToSpeechService : TextToSpeechService { private val synthesizer = AVSpeechSynthesizer() override suspend fun voices(language: String?): List { val all = AVSpeechSynthesisVoice.speechVoices() @Suppress("UNCHECKED_CAST") val typed = all as List return typed.filter { language.isNullOrBlank() || it.language.equals(language, ignoreCase = true) } .map { it.name } } override suspend fun speak( text: String, request: TextToSpeechRequest, onProgress: (startOffset: Int, endOffset: Int) -> Unit, ) { if (text.isBlank()) return val utterance = AVSpeechUtterance.speechUtteranceWithString(text) val resolvedVoice = when { !request.voice.isNullOrBlank() -> { val all = AVSpeechSynthesisVoice.speechVoices() @Suppress("UNCHECKED_CAST") (all as List).firstOrNull { it.name == request.voice } } !request.language.isNullOrBlank() -> AVSpeechSynthesisVoice.voiceWithLanguage(request.language) else -> null } resolvedVoice?.let { utterance.voice = it } utterance.rate = request.speechRate.toFloat().coerceIn(0.0f, 1.0f) utterance.pitchMultiplier = request.pitch.toFloat().coerceIn(0.5f, 2.0f) synthesizer.speakUtterance(utterance) val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500) val wordDelayMillis = (60_000L / wordsPerMinute).coerceAtLeast(40L) try { Regex("\\S+").findAll(text).forEach { word -> if (!synthesizer.speaking) return@forEach onProgress(word.range.first, word.range.last + 1) delay(wordDelayMillis) } while (synthesizer.speaking) delay(50) } finally { // Cancelled mid-utterance: don't leave the synthesizer talking. if (synthesizer.speaking) synthesizer.stopSpeakingAtBoundary(AVSpeechBoundary.AVSpeechBoundaryImmediate) } } override suspend fun stop() { synthesizer.stopSpeakingAtBoundary(AVSpeechBoundary.AVSpeechBoundaryImmediate) } }