Composables
Docs Login
Vela

Voice chat

package com.composables.vela

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.composables.vela.components.Icon
import com.composables.vela.components.IconButton
import com.composables.vela.components.IconButtonVariant
import com.composables.vela.components.ScreenScaffold
import com.composables.vela.components.Text
import com.composables.vela.components.VoiceOrb
import com.composables.vela.components.VoiceState
import com.composables.vela.theme.Icons
import com.composables.vela.theme.Microphone
import com.composables.vela.theme.MicrophoneSlash
import com.composables.vela.theme.SlidersHorizontal
import com.composables.vela.theme.Space
import com.composables.vela.theme.Theme
import com.composables.vela.theme.X
import com.composeunstyled.UnstyledButton
import kotlinx.coroutines.delay

@Composable
fun VoiceScreen(
    navigateHome: () -> Unit,
    modifier: Modifier = Modifier,
) {
    fun endVoiceChat() {
        // terminate the voice chat here
        navigateHome()
    }

    val preferences = rememberVoicePreferences()
    var showSettings by remember { mutableStateOf(false) }
    var muted by remember { mutableStateOf(false) }
    var state by remember { mutableStateOf(VoiceState.Listening) }
    var exchange by remember { mutableIntStateOf(0) }
    var heard by remember { mutableStateOf("") }
    var spoken by remember { mutableStateOf("") }
    var talking by remember { mutableStateOf(false) }
    val current = voiceExchanges.getOrNull(exchange)

    fun interruptAndListen() {
        exchange++
    }

    LaunchedEffect(exchange, muted, preferences.handsFree, talking) {
        if (current == null || muted) {
            if (muted) state = VoiceState.Muted
            return@LaunchedEffect
        }
        if (!preferences.handsFree && !talking && state != VoiceState.Hearing) {
            state = VoiceState.Listening
            return@LaunchedEffect
        }
        if (state != VoiceState.Hearing) {
            state = VoiceState.Listening
            spoken = ""
            heard = ""
            if (preferences.handsFree) delay(1400)
            state = VoiceState.Hearing
        }
        val words = current.said.split(" ")
        for (count in heard.split(" ").filter { it.isNotEmpty() }.size until words.size) {
            if (!preferences.handsFree && !talking) break
            heard = words.take(count + 1).joinToString(" ")
            delay(150)
        }
        if (!preferences.handsFree && talking) return@LaunchedEffect
        heard = current.said
        state = VoiceState.Thinking
        delay(900)
        state = VoiceState.Speaking
        current.reply.split(" ").forEachIndexed { index, _ ->
            spoken = current.reply.split(" ").take(index + 1).joinToString(" ")
            delay(
                if (preferences.speed == "Faster") 140
                else if (preferences.speed == "Slower") 280 else 200
            )
        }
        delay(800)
        exchange++
    }

    ScreenScaffold(modifier) {
        Column(
            Modifier.fillMaxSize()
                .windowInsetsPadding(
                    WindowInsets.systemBars.union(
                        WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal)
                    )
                )
                .padding(Space * 4),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Column(
                Modifier.weight(1f).fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Bottom,
            ) {
                UnstyledButton(
                    onClick = ::interruptAndListen,
                    enabled = state == VoiceState.Speaking,
                    modifier = Modifier.weight(1f, fill = false),
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                ) {
                    VoiceOrb(state)
                }
                AnimatedContent(
                    targetState = statusText(state, preferences.handsFree, current == null),
                    transitionSpec = { fadeIn() togetherWith fadeOut() },
                    label = "Voice status",
                    modifier = Modifier.padding(vertical = Space * 3),
                ) { status ->
                    Text(
                        status,
                        color = Theme.colors.onBackgroundMuted,
                        modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite },
                    )
                }
            }
            val transcript = rememberScrollState()
            LaunchedEffect(spoken, heard) { transcript.animateScrollTo(transcript.maxValue) }
            Column(
                Modifier.weight(1f)
                    .widthIn(max = 560.dp)
                    .fillMaxWidth()
                    .verticalScroll(transcript)
                    .padding(bottom = Space * 4),
                verticalArrangement = Arrangement.spacedBy(Space * 3),
            ) {
                if (heard.isNotEmpty()) {
                    Text(
                        heard,
                        color = Theme.colors.onBackgroundMuted,
                        style = Theme.typography.body.copy(textAlign = TextAlign.Center),
                        modifier = Modifier.fillMaxWidth(),
                    )
                }
                if (spoken.isNotEmpty()) {
                    Text(
                        spoken,
                        style = Theme.typography.title.copy(textAlign = TextAlign.Center),
                        modifier =
                            Modifier.fillMaxWidth().semantics {
                                liveRegion = LiveRegionMode.Polite
                            },
                    )
                }
            }
            Row(
                Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                IconButton(
                    onClick = { showSettings = true },
                    contentDescription = "Voice settings",
                    variant = IconButtonVariant.Tonal,
                ) {
                    Icon(
                        Icons.SlidersHorizontal,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp),
                    )
                }
                if (preferences.handsFree) {
                    IconButton(
                        onClick = { muted = !muted },
                        contentDescription = if (muted) "Unmute" else "Mute",
                        variant = if (muted) IconButtonVariant.Filled else IconButtonVariant.Tonal,
                    ) {
                        Icon(
                            if (muted) Icons.MicrophoneSlash else Icons.Microphone,
                            contentDescription = null,
                            modifier = Modifier.size(20.dp),
                        )
                    }
                } else {
                    IconButton(
                        onClick = { talking = !talking },
                        contentDescription = if (talking) "Send" else "Talk",
                        variant =
                            if (talking) IconButtonVariant.Filled else IconButtonVariant.Tonal,
                    ) {
                        Icon(
                            Icons.Microphone,
                            contentDescription = null,
                            modifier = Modifier.size(20.dp),
                        )
                    }
                }
                IconButton(
                    onClick = ::endVoiceChat,
                    contentDescription = "End voice chat",
                    variant = IconButtonVariant.Tonal,
                ) {
                    Icon(Icons.X, contentDescription = null, modifier = Modifier.size(20.dp))
                }
            }
        }
        VoiceSettingsSheet(
            visible = showSettings,
            onDismiss = { showSettings = false },
            preferences = preferences,
        )
    }
}

private fun statusText(state: VoiceState, handsFree: Boolean, finished: Boolean) =
    when {
        state == VoiceState.Muted -> "Microphone off"
        finished -> "Say something, or end the chat"
        state == VoiceState.Listening ->
            if (handsFree) "Listening" else "Tap the microphone to talk"
        state == VoiceState.Hearing -> "Listening"
        state == VoiceState.Thinking -> "Thinking"
        else -> "Tap the orb to interrupt"
    }

More screens from Vela

by Alex Styl

Search screens and components

Screen flows

Screens

UI Elements

One Android lesson, every Wednesday

Building Android apps?

What Alex learned building Android apps for 14 years, so you don't have to. Reads in under a minute.

Join 3,500+ Android developers. Unsubscribe any time.

You're subscribed

The next lesson lands in on Wednesday.