324 lines
7.8 KiB
Vue
324 lines
7.8 KiB
Vue
<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";
|
|
|
|
/**
|
|
* 注意:下面的 Web Speech API 只是文档演示用的适配器,不属于 AiChatComposer。
|
|
* 组件本身不包含 ASR;换成服务端流式识别或原生桥接时,只需回写 voiceState / voiceText。
|
|
*/
|
|
|
|
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>
|