Yokan / rebuild
Course 1 8624561

TextToSpeechService.ios.kt

composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/tts/TextToSpeechService.ios.kt

implementation61 lines
1package eu.friedcutlet.yokan.services.tts23import kotlinx.coroutines.delay45import platform.AVFAudio.AVSpeechBoundary6import platform.AVFAudio.AVSpeechSynthesisVoice7import platform.AVFAudio.AVSpeechSynthesizer8import platform.AVFAudio.AVSpeechUtterance910actual fun createPlatformTextToSpeechService(): TextToSpeechService = IosTextToSpeechService()1112private class IosTextToSpeechService : TextToSpeechService {13    private val synthesizer = AVSpeechSynthesizer()1415    override suspend fun voices(language: String?): List<String> {16        val all = AVSpeechSynthesisVoice.speechVoices()17        @Suppress("UNCHECKED_CAST")18        val typed = all as List<AVSpeechSynthesisVoice>19        return typed.filter { language.isNullOrBlank() || it.language.equals(language, ignoreCase = true) }20            .map { it.name }21    }2223    override suspend fun speak(24        text: String,25        request: TextToSpeechRequest,26        onProgress: (startOffset: Int, endOffset: Int) -> Unit,27    ) {28        if (text.isBlank()) return29        val utterance = AVSpeechUtterance.speechUtteranceWithString(text)30        val resolvedVoice = when {31            !request.voice.isNullOrBlank() -> {32                val all = AVSpeechSynthesisVoice.speechVoices()33                @Suppress("UNCHECKED_CAST")34                (all as List<AVSpeechSynthesisVoice>).firstOrNull { it.name == request.voice }35            }36            !request.language.isNullOrBlank() -> AVSpeechSynthesisVoice.voiceWithLanguage(request.language)37            else -> null38        }39        resolvedVoice?.let { utterance.voice = it }40        utterance.rate = request.speechRate.toFloat().coerceIn(0.0f, 1.0f)41        utterance.pitchMultiplier = request.pitch.toFloat().coerceIn(0.5f, 2.0f)42        synthesizer.speakUtterance(utterance)43        val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500)44        val wordDelayMillis = (60_000L / wordsPerMinute).coerceAtLeast(40L)45        try {46            Regex("\\S+").findAll(text).forEach { word ->47                if (!synthesizer.speaking) return@forEach48                onProgress(word.range.first, word.range.last + 1)49                delay(wordDelayMillis)50            }51            while (synthesizer.speaking) delay(50)52        } finally {53            // Cancelled mid-utterance: don't leave the synthesizer talking.54            if (synthesizer.speaking) synthesizer.stopSpeakingAtBoundary(AVSpeechBoundary.AVSpeechBoundaryImmediate)55        }56    }5758    override suspend fun stop() {59        synthesizer.stopSpeakingAtBoundary(AVSpeechBoundary.AVSpeechBoundaryImmediate)60    }61}62

Search chapters, reference and source filenames.