Yokan / rebuild
Course 1 8624561

TextToSpeechService.android.kt

composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/tts/TextToSpeechService.android.kt

implementation102 lines
1package eu.friedcutlet.yokan.services.tts23import eu.friedcutlet.yokan.AndroidAppContext4import android.os.Build5import android.speech.tts.TextToSpeech6import android.speech.tts.UtteranceProgressListener7import java.util.Locale8import kotlinx.coroutines.CancellationException9import kotlinx.coroutines.CompletableDeferred10import kotlinx.coroutines.suspendCancellableCoroutine11import kotlinx.coroutines.sync.Mutex12import kotlinx.coroutines.sync.withLock13import kotlin.coroutines.resume1415actual fun createPlatformTextToSpeechService(): TextToSpeechService = AndroidTextToSpeechService()1617/**18 * Holds one engine bound to the application context until its owner closes;19 * init is single-flight so concurrent callers never bind (and leak) extra engines.20 */21private class AndroidTextToSpeechService : TextToSpeechService {22    private val engineLock = Mutex()23    @Volatile private var tts: TextToSpeech? = null2425    private suspend fun engine(): TextToSpeech? = engineLock.withLock {26        tts?.let { return@withLock it }27        val context = AndroidAppContext.appContext ?: return@withLock null28        val ready = CompletableDeferred<Boolean>()29        val instance = TextToSpeech(context) { status ->30            ready.complete(status == TextToSpeech.SUCCESS)31        }32        val ok = try {33            ready.await()34        } catch (cancelled: CancellationException) {35            instance.shutdown()36            throw cancelled37        }38        if (ok) {39            instance.also { tts = it }40        } else {41            instance.shutdown()42            null43        }44    }4546    override suspend fun voices(language: String?): List<String> {47        val engine = engine() ?: return emptyList()48        val all = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {49            engine.voices.orEmpty()50        } else {51            emptyList()52        }53        return all.filter { language.isNullOrBlank() || it.locale.language.equals(language, ignoreCase = true) }54            .map { it.name }55            .distinct()56    }5758    override suspend fun speak(59        text: String,60        request: TextToSpeechRequest,61        onProgress: (startOffset: Int, endOffset: Int) -> Unit,62    ) {63        val engine = engine() ?: return64        if (!request.language.isNullOrBlank()) {65            engine.language = Locale.forLanguageTag(request.language)66        }67        if (!request.voice.isNullOrBlank() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {68            engine.voices?.firstOrNull { it.name == request.voice }?.let { engine.voice = it }69        }70        engine.setSpeechRate(request.speechRate.toFloat())71        engine.setPitch(request.pitch.toFloat())72        suspendCancellableCoroutine<Unit> { continuation ->73            val utteranceId = "${text.hashCode()}:${System.nanoTime()}"74            engine.setOnUtteranceProgressListener(object : UtteranceProgressListener() {75                override fun onStart(id: String?) = Unit76                override fun onDone(id: String?) {77                    if (id == utteranceId && continuation.isActive) continuation.resume(Unit)78                }79                @Deprecated("Required override")80                override fun onError(id: String?) {81                    if (id == utteranceId && continuation.isActive) continuation.resume(Unit)82                }83                override fun onRangeStart(id: String?, start: Int, end: Int, frame: Int) {84                    if (id == utteranceId) onProgress(start, end)85                }86            })87            engine.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId)88            continuation.invokeOnCancellation { engine.stop() }89        }90    }9192    override suspend fun stop() {93        tts?.stop()94    }9596    override suspend fun closeAndJoin() = engineLock.withLock {97        val engine = tts ?: return@withLock98        engine.stop()99        engine.shutdown()100        tts = null101    }102}103

Search chapters, reference and source filenames.