JavaScript高级实战:构建智能语音交互Web应用
一、系统架构设计
语音输入 + 意图识别 + 命令执行 + 语音反馈
二、核心功能实现
1. 语音识别初始化
class VoiceControl {
constructor() {
this.recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
this.recognition.continuous = true;
this.recognition.interimResults = true;
this.recognition.lang = 'zh-CN';
this.commands = new Map();
this.isListening = false;
this.setupEventListeners();
}
setupEventListeners() {
this.recognition.onresult = (event) => {
const last = event.results.length - 1;
const transcript = event.results[last][0].transcript.trim();
this.processCommand(transcript);
};
this.recognition.onerror = (event) => {
console.error('语音识别错误:', event.error);
};
}
2. 命令注册与处理
registerCommand(pattern, callback) {
this.commands.set(
typeof pattern === 'string' ? new RegExp(pattern, 'i') : pattern,
callback
);
}
processCommand(transcript) {
for (const [pattern, callback] of this.commands) {
const match = transcript.match(pattern);
if (match) {
callback(...match.slice(1));
break;
}
}
}
start() {
if (!this.isListening) {
this.recognition.start();
this.isListening = true;
}
}
stop() {
if (this.isListening) {
this.recognition.stop();
this.isListening = false;
}
}
}
3. 语音合成反馈
class VoiceFeedback {
constructor() {
this.synth = window.speechSynthesis;
this.utterance = new SpeechSynthesisUtterance();
this.utterance.lang = 'zh-CN';
this.utterance.rate = 1;
this.utterance.pitch = 1;
}
speak(text) {
return new Promise((resolve) => {
this.utterance.text = text;
this.utterance.onend = resolve;
this.synth.speak(this.utterance);
});
}
setVoice(name) {
const voices = this.synth.getVoices();
const voice = voices.find(v => v.name.includes(name));
if (voice) this.utterance.voice = voice;
}
}
三、高级功能实现
1. 多语言支持
class I18nVoiceControl extends VoiceControl {
constructor(lang = 'zh-CN') {
super();
this.setLanguage(lang);
this.translations = new Map();
}
setLanguage(lang) {
this.recognition.lang = lang;
this.feedback.utterance.lang = lang;
}
addTranslation(key, translations) {
this.translations.set(key, translations);
}
t(key, lang) {
return this.translations.get(key)?.[lang] || key;
}
}
2. 语音指令链
class VoiceCommandChain {
constructor(voiceControl) {
this.voiceControl = voiceControl;
this.commandQueue = [];
this.isProcessing = false;
}
addCommand(pattern, ...actions) {
this.voiceControl.registerCommand(pattern, async (...args) => {
this.commandQueue.push({ actions, args });
if (!this.isProcessing) this.processQueue();
});
}
async processQueue() {
this.isProcessing = true;
while (this.commandQueue.length > 0) {
const { actions, args } = this.commandQueue.shift();
for (const action of actions) {
await action(...args);
}
}
this.isProcessing = false;
}
}
四、实战案例演示
1. 网页语音控制
const voiceCtrl = new VoiceControl();
const feedback = new VoiceFeedback();
voiceCtrl.registerCommand('滚动到顶部', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
feedback.speak('已滚动到页面顶部');
});
voiceCtrl.registerCommand(/搜索(.+)/, (query) => {
window.open(`https://www.baidu.com/s?wd=${encodeURIComponent(query)}`);
feedback.speak(`正在搜索${query}`);
});
// 启动语音监听
document.getElementById('start-btn').addEventListener('click', () => {
voiceCtrl.start();
feedback.speak('语音控制已启动');
});
2. 性能优化方案
- 节流处理:防止频繁触发命令
- 离线语音包:使用本地语音模型
- Web Worker:语音识别在后台线程运行
- 缓存策略:常用命令结果缓存

