vue实现语音
Vue 实现语音功能
在 Vue 中实现语音功能通常涉及语音识别(Speech-to-Text)和语音合成(Text-to-Speech)。以下是实现这两种功能的详细方法。

语音识别(Speech-to-peech)
使用 Web Speech API 实现语音识别功能:

// 在 Vue 组件中
export default {
data() {
return {
recognition: null,
transcript: '',
isListening: false
}
},
methods: {
startListening() {
this.recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)()
this.recognition.lang = 'zh-CN' // 设置语言
this.recognition.interimResults = true
this.recognition.onresult = (event) => {
const transcript = Array.from(event.results)
.map(result => result[0])
.map(result => result.transcript)
.join('')
this.transcript = transcript
}
this.recognition.onerror = (event) => {
console.error('语音识别错误:', event.error)
}
this.recognition.start()
this.isListening = true
},
stopListening() {
if (this.recognition) {
this.recognition.stop()
this.isListening = false
}
}
},
beforeDestroy() {
if (this.recognition) {
this.recognition.stop()
}
}
}
语音合成(Text-to-Speech)
使用 Web Speech API 实现语音合成功能:
// 在 Vue 组件中
export default {
methods: {
speak(text) {
const utterance = new SpeechSynthesisUtterance(text)
utterance.lang = 'zh-CN' // 设置语言
utterance.rate = 1 // 语速
utterance.pitch = 1 // 音高
window.speechSynthesis.speak(utterance)
},
stopSpeaking() {
window.speechSynthesis.cancel()
}
}
}
第三方库集成
如果需要更复杂的功能,可以集成第三方语音识别库如 annyang 或 vue-voice-recognition:
npm install annyang
// 使用 annyang
import annyang from 'annyang'
export default {
mounted() {
if (annyang) {
annyang.addCommands({
'你好': () => {
alert('你好!')
},
'打开菜单': () => {
this.openMenu()
}
})
annyang.start()
}
},
beforeDestroy() {
if (annyang) {
annyang.abort()
}
}
}
注意事项
- Web Speech API 的兼容性有限,建议在使用前检查浏览器支持情况。
- 语音识别功能需要用户授权麦克风权限。
- 中文支持可能需要额外配置语言参数。
- 生产环境中建议使用更稳定的第三方语音服务(如阿里云、腾讯云的语音识别 API)。






