Spoken conversation mode: listen again after each spoken answer until stopped
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
- A spoken question answered aloud opens a conversation (Settings › Assistant, on by default, needs voice replies); after the answer is heard to the end, the sheet listens again. - Ends on a stop phrase (assist_stop_words, per language; isStopPhrase), End, typing, a stopped voice, a card waiting, or nothing said (the existing silence timeout). - "In conversation" banner with End in the sheet's foot; shot 24-assistant-conversation. - HeadsetRoute: a Bluetooth headset made the communication device (Android 12+) and its microphone preferred by the recorder, so the conversation can stay in the ear. - Speaker.playToEnd tells a voice heard to the end from one stopped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
21 files changed
+304
-12
No files matched your search
@@ -71,6 +71,11 @@ data class AssistUiState(
|
||||
val speaking: Boolean = false,
|
||||
/** Whether anything can turn speech into words: the instance's speech-to-text, or the phone's. */
|
||||
val canListen: Boolean = true,
|
||||
/**
|
||||
* A spoken conversation: after each spoken answer is read aloud, the sheet listens again --
|
||||
* until the person says stop, taps End, types, or says nothing.
|
||||
*/
|
||||
val conversation: Boolean = false,
|
||||
) {
|
||||
val screenAvailable: Boolean get() = screenText || screenshot != null
|
||||
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
|
||||
@@ -94,6 +99,7 @@ interface AssistActions {
|
||||
fun voiceReply(on: Boolean) {}
|
||||
fun readAloud() {}
|
||||
fun stopReading() {}
|
||||
fun endConversation() {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -116,6 +122,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
private val recorder = Recorder(scope)
|
||||
private val phone = PhoneRecognizer(context)
|
||||
private val speaker = Speaker(context)
|
||||
private val route = HeadsetRoute(context)
|
||||
private var following: Job? = null
|
||||
private var hearing: Job? = null
|
||||
private var usingPhone = false
|
||||
@@ -215,13 +222,15 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
_state.update { it.copy(listening = true, heard = "", level = 0f, error = null) }
|
||||
hearing = scope.launch {
|
||||
usingPhone = phoneEngine()
|
||||
// A headset's microphone when one is there: the conversation can go on in the ear.
|
||||
val headset = route.microphone()
|
||||
if (usingPhone) {
|
||||
phone.start(
|
||||
onPartial = { words -> _state.update { it.copy(heard = words) } },
|
||||
onLevel = { l -> _state.update { it.copy(level = l) } },
|
||||
onResult = { words ->
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "") }
|
||||
if (words.isNotBlank()) ask(words, spoken = true)
|
||||
if (words.isNotBlank()) askOrStop(words) else endConversation()
|
||||
},
|
||||
onFail = { code ->
|
||||
val quiet = code == SpeechRecognizer.ERROR_NO_MATCH || code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT
|
||||
@@ -229,12 +238,14 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
it.copy(
|
||||
listening = false,
|
||||
level = 0f,
|
||||
conversation = false,
|
||||
error = if (quiet) null else context.getString(R.string.assist_recogniser_failed),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
recorder.preferred = headset
|
||||
recorder.start()
|
||||
launch { recorder.level.collect { l -> _state.update { it.copy(level = l) } } }
|
||||
launch { writeDownAsSaid() }
|
||||
@@ -317,20 +328,33 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
_state.update { it.copy(busy = true) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
_state.update { it.copy(busy = false, heard = "") }
|
||||
if (text.isNotBlank()) ask(text, spoken = true)
|
||||
if (text.isNotBlank()) askOrStop(text) else endConversation()
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, heard = "", error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop listening and keep nothing: the person would rather type. */
|
||||
/**
|
||||
* Stop listening and keep nothing: the person would rather type -- or said nothing at all.
|
||||
* Either ends a spoken conversation.
|
||||
*/
|
||||
override fun type() {
|
||||
hearing?.cancel()
|
||||
hearing = null
|
||||
phone.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
_state.update { it.copy(listening = false, heard = "", level = 0f) }
|
||||
_state.update { it.copy(listening = false, heard = "", level = 0f, conversation = false) }
|
||||
}
|
||||
|
||||
/** What was said: in a conversation, "stop" (or the like) ends it; anything else is asked. */
|
||||
private fun askOrStop(words: String) {
|
||||
val phrases = context.getString(R.string.assist_stop_words).split("|")
|
||||
if (_state.value.conversation && isStopPhrase(words, phrases)) endConversation() else ask(words, spoken = true)
|
||||
}
|
||||
|
||||
override fun endConversation() {
|
||||
_state.update { it.copy(conversation = false) }
|
||||
}
|
||||
|
||||
// --- Asking ------------------------------------------------------------------------------
|
||||
@@ -349,6 +373,10 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
following = scope.launch {
|
||||
val turn = AssistTurn(question)
|
||||
_state.update { it.copy(busy = true, turns = it.turns + turn, error = null) }
|
||||
// A spoken question, answered aloud, opens a conversation (Settings › Assistant).
|
||||
val talking = spoken && context.lembas.instances.prefs.first().assistantConversation &&
|
||||
_state.value.voiceReply && _state.value.canSpeak
|
||||
_state.update { it.copy(conversation = talking) }
|
||||
try {
|
||||
val store = context.lembas.instances
|
||||
val api = store.client() ?: throw ApiException(401, "Not signed in.")
|
||||
@@ -384,9 +412,16 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
live = live.apply(frame.event, frame.data)
|
||||
_state.update { s -> s.copy(turns = s.turns.dropLast(1) + turn.copy(reply = live), busy = live.finished == null) }
|
||||
}
|
||||
if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null) speak(spokenWords(live.finished?.steps.orEmpty()))
|
||||
val heardAll = if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null && live.cards.isEmpty()) {
|
||||
speak(spokenWords(live.finished?.steps.orEmpty()))
|
||||
} else {
|
||||
false
|
||||
}
|
||||
// The answer was heard to the end: listen for the next thing said. Stopped, a
|
||||
// card waiting, or nothing to read: the conversation ends there.
|
||||
if (_state.value.conversation && heardAll && micAllowed()) listen() else endConversation()
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
_state.update { it.copy(error = context.explain(e), conversation = false) }
|
||||
} finally {
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
@@ -422,7 +457,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
override fun newChat() {
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false) }
|
||||
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false, conversation = false) }
|
||||
}
|
||||
|
||||
/** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */
|
||||
@@ -449,15 +484,18 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
scope.launch { speak(spokenWords(steps)) }
|
||||
}
|
||||
|
||||
/** Stop the voice -- and, in a conversation, the listening that would follow it. */
|
||||
override fun stopReading() = speaker.stop()
|
||||
|
||||
private suspend fun speak(words: String) {
|
||||
if (words.isBlank()) return
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: return
|
||||
speaker.play(api.speech(words))
|
||||
/** Read [words] aloud; true when they were heard to the end. */
|
||||
private suspend fun speak(words: String): Boolean {
|
||||
if (words.isBlank()) return false
|
||||
return try {
|
||||
val api = context.lembas.instances.client() ?: return false
|
||||
speaker.playToEnd(api.speech(words))
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,6 +510,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
hearing?.cancel()
|
||||
speaker.stop()
|
||||
phone.stop()
|
||||
route.release()
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ import androidx.compose.material.icons.automirrored.filled.VolumeOff
|
||||
import androidx.compose.material.icons.automirrored.filled.VolumeUp
|
||||
import androidx.compose.material.icons.filled.ArrowDropDown
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Keyboard
|
||||
import androidx.compose.material.icons.filled.Lightbulb
|
||||
@@ -276,6 +277,7 @@ fun ColumnScope.AssistSheetContent(
|
||||
|
||||
// The foot.
|
||||
Column(Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, top = 4.dp, bottom = 12.dp)) {
|
||||
if (state.conversation && !locked) Conversation(actions)
|
||||
if (state.screenAvailable && !locked) ScreenToggle(state, actions)
|
||||
if (state.listening) {
|
||||
Listening(state, onDone = actions::heard, onType = actions::type)
|
||||
@@ -498,6 +500,28 @@ private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A spoken conversation is on: the sheet will listen again after the answer is read. Says so,
|
||||
* and how it ends -- End here, "stop" said, or silence. The words give; End keeps its size.
|
||||
*/
|
||||
@Composable
|
||||
private fun Conversation(actions: AssistActions) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(shape = RoundedCornerShape(16.dp), color = palette.accentSoft, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
|
||||
Row(Modifier.padding(start = 14.dp, end = 4.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Forum, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.assist_conversation), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
Text(stringResource(R.string.assist_conversation_line), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
TextButton(onClick = actions::endConversation, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.assist_conversation_end))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Use screen: off every time the sheet opens; on, the screen goes with the next question only. */
|
||||
@Composable
|
||||
private fun ScreenToggle(state: AssistUiState, actions: AssistActions) {
|
||||
|
||||
@@ -5,7 +5,9 @@ import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioDeviceInfo
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioManager
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaPlayer
|
||||
import android.media.MediaRecorder
|
||||
@@ -17,6 +19,7 @@ import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.annotation.RequiresPermission
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -56,6 +59,9 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
/** How many seconds have been recorded. */
|
||||
val seconds: Float get() = pcm.size() / (RATE * 2f)
|
||||
|
||||
/** The microphone to prefer -- a headset's, while one is the route ([HeadsetRoute]). */
|
||||
var preferred: AudioDeviceInfo? = null
|
||||
|
||||
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
|
||||
fun start() {
|
||||
if (record != null) return
|
||||
@@ -69,6 +75,7 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
maxOf(min, RATE),
|
||||
)
|
||||
record = audio
|
||||
preferred?.let { audio.setPreferredDevice(it) }
|
||||
audio.startRecording()
|
||||
job = scope.launch(Dispatchers.IO) {
|
||||
val buffer = ByteArray(maxOf(min, 4096))
|
||||
@@ -143,11 +150,15 @@ class Speaker(private val context: Context) {
|
||||
private val _playing = MutableStateFlow(false)
|
||||
val playing: StateFlow<Boolean> = _playing.asStateFlow()
|
||||
|
||||
private var ended: CompletableDeferred<Boolean>? = null
|
||||
|
||||
suspend fun play(mp3: ByteArray) {
|
||||
stop()
|
||||
val file = withContext(Dispatchers.IO) {
|
||||
File.createTempFile("reply", ".mp3", context.cacheDir).apply { writeBytes(mp3) }
|
||||
}
|
||||
val done = CompletableDeferred<Boolean>()
|
||||
ended = done
|
||||
player = MediaPlayer().apply {
|
||||
setAudioAttributes(
|
||||
AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ASSISTANT)
|
||||
@@ -159,6 +170,7 @@ class Speaker(private val context: Context) {
|
||||
file.delete()
|
||||
player = null
|
||||
_playing.value = false
|
||||
done.complete(true)
|
||||
}
|
||||
prepare()
|
||||
start()
|
||||
@@ -166,6 +178,12 @@ class Speaker(private val context: Context) {
|
||||
_playing.value = true
|
||||
}
|
||||
|
||||
/** Play [mp3] and wait: true when it was heard to the end, false when it was stopped. */
|
||||
suspend fun playToEnd(mp3: ByteArray): Boolean {
|
||||
play(mp3)
|
||||
return ended?.await() ?: false
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
player?.runCatching {
|
||||
stop()
|
||||
@@ -173,9 +191,58 @@ class Speaker(private val context: Context) {
|
||||
}
|
||||
player = null
|
||||
_playing.value = false
|
||||
ended?.complete(false)
|
||||
ended = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A headset's microphone for the assistant, while one is connected: a Bluetooth headset is
|
||||
* made the communication device (Android 12+), so the sheet hears the headset and answers into
|
||||
* it, as a call would; a wired headset's microphone is the default anyway. [release] gives the
|
||||
* route back. Nothing happens without a headset.
|
||||
*/
|
||||
class HeadsetRoute(context: Context) {
|
||||
private val audio = context.getSystemService(AudioManager::class.java)
|
||||
private var engaged = false
|
||||
|
||||
/** The headset's microphone, if there is one -- made the route first where that is needed. */
|
||||
fun microphone(): AudioDeviceInfo? {
|
||||
val inputs = audio?.getDevices(AudioManager.GET_DEVICES_INPUTS).orEmpty()
|
||||
val wired = inputs.firstOrNull { it.type == AudioDeviceInfo.TYPE_WIRED_HEADSET || it.type == AudioDeviceInfo.TYPE_USB_HEADSET }
|
||||
if (wired != null) return wired
|
||||
if (Build.VERSION.SDK_INT < 31 || audio == null) return null
|
||||
val headset = audio.availableCommunicationDevices.firstOrNull {
|
||||
it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || it.type == AudioDeviceInfo.TYPE_BLE_HEADSET
|
||||
} ?: return null
|
||||
if (!engaged) engaged = runCatching { audio.setCommunicationDevice(headset) }.getOrDefault(false)
|
||||
return inputs.firstOrNull { it.type == headset.type } ?: headset
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (engaged && Build.VERSION.SDK_INT >= 31) runCatching { audio?.clearCommunicationDevice() }
|
||||
engaged = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [heard] is the person ending a spoken conversation: one of [phrases] ("stop", "that's
|
||||
* all", in the app's language), alone or with a word or two around it ("stop please", "ok
|
||||
* that's all"). A longer sentence that happens to hold "stop" is a question, not an ending.
|
||||
*/
|
||||
fun isStopPhrase(heard: String, phrases: List<String>): Boolean {
|
||||
val said = words(heard)
|
||||
if (said.isEmpty()) return false
|
||||
return phrases.map(::words).filter { it.isNotEmpty() }.any { phrase ->
|
||||
said.size <= phrase.size + 2 && said.windowed(phrase.size).any { it == phrase }
|
||||
}
|
||||
}
|
||||
|
||||
private fun words(text: String): List<String> = text.lowercase()
|
||||
.replace(Regex("[\\u2019']"), "")
|
||||
.split(Regex("[^\\p{L}\\p{N}]+"))
|
||||
.filter { it.isNotBlank() }
|
||||
|
||||
/**
|
||||
* Speech in through the phone's own recogniser, for Settings › Voice input › Phone: words as
|
||||
* they are said ([start]'s `onPartial`), and the end of speech found by the recogniser.
|
||||
|
||||
@@ -85,6 +85,8 @@ data class Prefs(
|
||||
val accountLanguage: String = "",
|
||||
val voiceInput: String = VOICE_LEMBAS,
|
||||
val assistantListens: Boolean = true,
|
||||
/** After a spoken answer is read aloud, listen again: a spoken conversation. */
|
||||
val assistantConversation: Boolean = true,
|
||||
val assistantModel: String = "",
|
||||
val lastAssistChat: String = "",
|
||||
val lastAssistTitle: String = "",
|
||||
|
||||
@@ -29,6 +29,7 @@ import androidx.compose.material.icons.filled.Assistant
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Dns
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
@@ -102,6 +103,7 @@ interface SettingsActions {
|
||||
fun assistantTemporary(on: Boolean) {}
|
||||
fun voiceInput(value: String) {}
|
||||
fun assistantListens(on: Boolean) {}
|
||||
fun assistantConversation(on: Boolean) {}
|
||||
fun readAloud(on: Boolean) {}
|
||||
fun checkUpdate() {}
|
||||
fun openRelease() {}
|
||||
@@ -196,6 +198,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantListens = on) } }
|
||||
}
|
||||
|
||||
override fun assistantConversation(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantConversation = on) } }
|
||||
}
|
||||
|
||||
override fun readAloud(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } }
|
||||
}
|
||||
@@ -408,6 +414,21 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
onClick = { actions.readAloud(!state.prefs.readAloudSpoken) },
|
||||
trailing = { Switch(checked = state.prefs.readAloudSpoken, onCheckedChange = actions::readAloud) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Forum,
|
||||
stringResource(R.string.assistant_conversation),
|
||||
subtitle = stringResource(R.string.assistant_conversation_line),
|
||||
enabled = state.prefs.readAloudSpoken,
|
||||
onClick = { actions.assistantConversation(!state.prefs.assistantConversation) },
|
||||
trailing = {
|
||||
Switch(
|
||||
checked = state.prefs.assistantConversation && state.prefs.readAloudSpoken,
|
||||
enabled = state.prefs.readAloudSpoken,
|
||||
onCheckedChange = actions::assistantConversation,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.assistant_samsung) + "\n\n" + stringResource(R.string.assist_no_wake_word),
|
||||
|
||||
Reference in new issue
Block a user