docs(ai-chat-composer): add voice input demo
This commit is contained in:
@@ -10,6 +10,33 @@ demo-preview=../demos/ai-chat-composer/basic.vue
|
||||
|
||||
:::
|
||||
|
||||
## 语音输入
|
||||
|
||||
输入框为空且未聚焦时,长按 300ms 进入语音面板;松手发送,按住上滑可取消。组件只负责手势与状态展示,识别能力由业务侧接入。
|
||||
|
||||
:::preview 长按语音输入 || 长按输入框说话,松手发送,按住上滑取消;勾选「模拟识别」可直接预览交互
|
||||
|
||||
demo-preview=../demos/ai-chat-composer/voice.vue
|
||||
|
||||
:::
|
||||
|
||||
### 交互约定
|
||||
|
||||
- 短按(小于 300ms)仍然聚焦文本域;输入框有内容或已聚焦时不接管手势,避免影响编辑与选择
|
||||
- 触发后显示语音面板:`voiceText` 有值时优先展示,否则按 `voiceState` 显示 `voiceListeningText` 或 `voiceProcessingText`
|
||||
- 按住上滑超过 48px 后松手触发 `voice-cancel`,面板切换为 `voiceCancelHint`
|
||||
- `voiceEnabled` 默认关闭,需要显式开启
|
||||
|
||||
`voiceState` 由业务侧驱动:
|
||||
|
||||
| 状态 | 含义 |
|
||||
| --- | --- |
|
||||
| `idle` | 未在识别,面板关闭 |
|
||||
| `listening` | 正在聆听,实时回写 `voiceText` |
|
||||
| `processing` | 已松手,等待最终识别结果 |
|
||||
|
||||
识别完成或失败后回到 `idle`,面板随之关闭。识别结果不会自动写入输入框或发送,由业务侧在 `voice-stop` 后自行处理。想换文案时用 `voiceSendHint`、`voiceCancelHint`、`voiceListeningText`、`voiceProcessingText`。
|
||||
|
||||
## 何时使用
|
||||
|
||||
需要单独摆放输入框时使用。多数情况下直接用 [AiChatPanel](/components/ai-chat-panel) 更省事。
|
||||
@@ -33,6 +60,9 @@ demo-preview=../demos/ai-chat-composer/basic.vue
|
||||
- `retry`:点错误条上的重试
|
||||
- `new-conversation`:清空输入框并请求业务侧开始一个新会话
|
||||
- `add-attachment`:请求业务侧添加附件
|
||||
- `voice-start`:长按达到阈值,可以开始录音或启动识别
|
||||
- `voice-stop`:松手且未处于取消区域,可以停止识别并取最终结果
|
||||
- `voice-cancel`:上滑后松手,或指针被系统取消,应丢弃本次语音
|
||||
|
||||
输入框内容用 `v-model` 绑定,`maxLength` 默认 2000。
|
||||
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
<template>
|
||||
<div class="demo">
|
||||
<ai-chat-composer
|
||||
v-model="draft"
|
||||
:is-generating="generating"
|
||||
voice-enabled
|
||||
:voice-state="voiceState"
|
||||
:voice-text="voiceText"
|
||||
@send="sendMessage"
|
||||
@voice-start="onVoiceStart"
|
||||
@voice-stop="onVoiceStop"
|
||||
@voice-cancel="onVoiceCancel"
|
||||
/>
|
||||
|
||||
<div class="bar">
|
||||
<label class="mock">
|
||||
<input v-model="mockEnabled" type="checkbox" />
|
||||
<span v-text="'模拟识别'" />
|
||||
</label>
|
||||
<span class="hint" v-text="hint" />
|
||||
</div>
|
||||
|
||||
<ol class="log">
|
||||
<li v-for="(item, index) in log" :key="index" v-text="item" />
|
||||
</ol>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { AiChatComposer } from "timi-tdesign-mobile";
|
||||
|
||||
type VoiceState = "idle" | "listening" | "processing";
|
||||
|
||||
/** Web Speech API 的主入口不在 lib.dom 里,这里只声明演示用到的部分。 */
|
||||
interface SpeechRecognitionLike {
|
||||
lang: string;
|
||||
continuous: boolean;
|
||||
interimResults: boolean;
|
||||
onresult: ((event: SpeechResultEvent) => void) | null;
|
||||
onerror: ((event: SpeechErrorEvent) => void) | null;
|
||||
onend: (() => void) | null;
|
||||
start: () => void;
|
||||
stop: () => void;
|
||||
abort: () => void;
|
||||
}
|
||||
|
||||
interface SpeechResultEvent {
|
||||
resultIndex: number;
|
||||
results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }>;
|
||||
}
|
||||
|
||||
interface SpeechErrorEvent {
|
||||
error: string;
|
||||
}
|
||||
|
||||
type SpeechRecognitionConstructor = new () => SpeechRecognitionLike;
|
||||
|
||||
/** 模拟识别逐段吐出的文本,用来预览不说话也能看到的完整交互。 */
|
||||
const MOCK_STEPS = [
|
||||
"帮我",
|
||||
"帮我整理一下",
|
||||
"帮我整理一下上周的订单数据",
|
||||
"帮我整理一下上周的订单数据,并总结三条结论"
|
||||
];
|
||||
|
||||
const draft = ref("");
|
||||
const generating = ref(false);
|
||||
const log = ref<string[]>([]);
|
||||
const supported = ref(false);
|
||||
const mockEnabled = ref(false);
|
||||
const voiceState = ref<VoiceState>("idle");
|
||||
const voiceText = ref("");
|
||||
|
||||
let recognition: SpeechRecognitionLike | undefined;
|
||||
let finalText = "";
|
||||
let mockStepTimer: number | undefined;
|
||||
let mockFinishTimer: number | undefined;
|
||||
|
||||
const hint = computed(() => {
|
||||
if (mockEnabled.value) {
|
||||
return "模拟模式:按住输入框,松手发送,按住上滑取消。";
|
||||
}
|
||||
if (!supported.value) {
|
||||
return "当前浏览器不支持语音识别,已切换为模拟。";
|
||||
}
|
||||
return "长按输入框说话,松手发送;按住上滑可取消。";
|
||||
});
|
||||
|
||||
/** 获取浏览器实现;Chrome 与 Edge 需要 webkit 前缀。 */
|
||||
function getSpeechRecognition(): SpeechRecognitionConstructor | undefined {
|
||||
if (typeof window === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
const speechWindow = window as Window & {
|
||||
SpeechRecognition?: SpeechRecognitionConstructor;
|
||||
webkitSpeechRecognition?: SpeechRecognitionConstructor;
|
||||
};
|
||||
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition;
|
||||
}
|
||||
|
||||
function push(message: string): void {
|
||||
log.value = [`${new Date().toLocaleTimeString()} ${message}`, ...log.value].slice(0, 5);
|
||||
}
|
||||
|
||||
/** 所有发送入口共用:录音结果与手动输入都走这里。 */
|
||||
function sendMessage(message: string): void {
|
||||
const content = message.trim();
|
||||
if (!content) {
|
||||
push("没有识别到内容,请再试一次");
|
||||
return;
|
||||
}
|
||||
generating.value = true;
|
||||
push(`send("${content}")`);
|
||||
setTimeout(() => {
|
||||
generating.value = false;
|
||||
push("生成结束");
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
function onVoiceStart(): void {
|
||||
voiceText.value = "";
|
||||
finalText = "";
|
||||
if (mockEnabled.value || !supported.value) {
|
||||
startMock();
|
||||
return;
|
||||
}
|
||||
const SpeechRecognition = getSpeechRecognition();
|
||||
if (!SpeechRecognition) {
|
||||
startMock();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const instance = new SpeechRecognition();
|
||||
instance.lang = "zh-CN";
|
||||
instance.continuous = true;
|
||||
instance.interimResults = true;
|
||||
instance.onresult = handleResult;
|
||||
instance.onerror = handleError;
|
||||
instance.onend = handleEnd;
|
||||
instance.start();
|
||||
recognition = instance;
|
||||
voiceState.value = "listening";
|
||||
} catch {
|
||||
push("语音识别启动失败,已切换模拟识别");
|
||||
startMock();
|
||||
}
|
||||
}
|
||||
|
||||
function onVoiceStop(): void {
|
||||
if (voiceState.value !== "listening") {
|
||||
return;
|
||||
}
|
||||
if (mockStepTimer !== undefined) {
|
||||
stopMock();
|
||||
return;
|
||||
}
|
||||
if (!recognition) {
|
||||
resetVoice();
|
||||
return;
|
||||
}
|
||||
voiceState.value = "processing";
|
||||
try {
|
||||
recognition.stop();
|
||||
} catch {
|
||||
finishVoice(voiceText.value);
|
||||
}
|
||||
}
|
||||
|
||||
function onVoiceCancel(): void {
|
||||
push("已取消语音输入");
|
||||
resetVoice();
|
||||
}
|
||||
|
||||
/** 实时拼接最终结果与临时结果,喂给组件的语音面板。 */
|
||||
function handleResult(event: SpeechResultEvent): void {
|
||||
let interim = "";
|
||||
for (let index = event.resultIndex; index < event.results.length; index += 1) {
|
||||
const result = event.results[index];
|
||||
const transcript = result[0]?.transcript ?? "";
|
||||
if (result.isFinal) {
|
||||
finalText += transcript;
|
||||
} else {
|
||||
interim += transcript;
|
||||
}
|
||||
}
|
||||
voiceText.value = (finalText + interim).trim();
|
||||
}
|
||||
|
||||
function handleError(event: SpeechErrorEvent): void {
|
||||
if (event.error === "aborted") {
|
||||
return;
|
||||
}
|
||||
const messages: Record<string, string> = {
|
||||
"not-allowed": "麦克风权限被拒绝,可勾选「模拟识别」再试",
|
||||
"service-not-allowed": "当前环境不允许语音识别,可勾选「模拟识别」再试",
|
||||
"audio-capture": "没有找到可用的麦克风",
|
||||
network: "语音服务不可用,可勾选「模拟识别」再试",
|
||||
"no-speech": "没有听到声音,请再试一次"
|
||||
};
|
||||
push(messages[event.error] ?? `语音识别失败:${event.error}`);
|
||||
resetVoice();
|
||||
}
|
||||
|
||||
function handleEnd(): void {
|
||||
recognition = undefined;
|
||||
voiceState.value = "processing";
|
||||
finishVoice(voiceText.value);
|
||||
}
|
||||
|
||||
function finishVoice(text: string): void {
|
||||
const message = text.trim();
|
||||
resetVoice();
|
||||
sendMessage(message);
|
||||
}
|
||||
|
||||
function startMock(): void {
|
||||
voiceState.value = "listening";
|
||||
voiceText.value = "";
|
||||
let step = 0;
|
||||
mockStepTimer = window.setInterval(() => {
|
||||
voiceText.value = MOCK_STEPS[Math.min(step, MOCK_STEPS.length - 1)];
|
||||
step += 1;
|
||||
}, 500);
|
||||
}
|
||||
|
||||
function stopMock(): void {
|
||||
if (mockStepTimer !== undefined) {
|
||||
window.clearInterval(mockStepTimer);
|
||||
mockStepTimer = undefined;
|
||||
}
|
||||
voiceState.value = "processing";
|
||||
mockFinishTimer = window.setTimeout(() => {
|
||||
mockFinishTimer = undefined;
|
||||
finishVoice(voiceText.value || MOCK_STEPS[0]);
|
||||
}, 600);
|
||||
}
|
||||
|
||||
/** 释放识别实例与定时器;abort 用于取消,正常结束则只解绑回调。 */
|
||||
function resetVoice(): void {
|
||||
if (recognition) {
|
||||
const instance = recognition;
|
||||
recognition = undefined;
|
||||
instance.onresult = null;
|
||||
instance.onerror = null;
|
||||
instance.onend = null;
|
||||
try {
|
||||
instance.abort();
|
||||
} catch {
|
||||
// 实例可能已自行结束,忽略
|
||||
}
|
||||
}
|
||||
if (mockStepTimer !== undefined) {
|
||||
window.clearInterval(mockStepTimer);
|
||||
mockStepTimer = undefined;
|
||||
}
|
||||
if (mockFinishTimer !== undefined) {
|
||||
window.clearTimeout(mockFinishTimer);
|
||||
mockFinishTimer = undefined;
|
||||
}
|
||||
voiceState.value = "idle";
|
||||
voiceText.value = "";
|
||||
finalText = "";
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
supported.value = Boolean(getSpeechRecognition());
|
||||
mockEnabled.value = !supported.value;
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
resetVoice();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.demo {
|
||||
.bar {
|
||||
display: flex;
|
||||
gap: .5rem;
|
||||
align-items: center;
|
||||
margin-top: .75rem;
|
||||
}
|
||||
|
||||
.mock {
|
||||
gap: .25rem;
|
||||
display: inline-flex;
|
||||
font-size: .75rem;
|
||||
cursor: pointer;
|
||||
color: var(--vp-c-text-2);
|
||||
align-items: center;
|
||||
|
||||
input {
|
||||
cursor: pointer;
|
||||
accent-color: var(--vp-c-brand-1);
|
||||
}
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: .75rem;
|
||||
line-height: 1.4;
|
||||
color: var(--vp-c-text-2);
|
||||
}
|
||||
|
||||
.log {
|
||||
margin: .75rem 0 0;
|
||||
padding-left: 1.25rem;
|
||||
font-size: .75rem;
|
||||
font-family: monospace;
|
||||
color: var(--vp-c-text-2);
|
||||
|
||||
li {
|
||||
margin-bottom: .25rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user