vue实现读单词拼写
实现思路
在Vue中实现单词拼读功能,可以通过Web Speech API的SpeechSynthesis接口完成。核心步骤包括获取浏览器语音合成支持、配置发音参数(如语速、语调)、触发单词朗读。
代码实现
<template>
<div>
<input v-model="word" placeholder="输入单词" />
<button @click="speakWord">朗读单词</button>
<button @click="spellWord">拼写单词</button>
</div>
</template>
<script>
export default {
data() {
return {
word: '',
voices: [],
synth: window.speechSynthesis
}
},
mounted() {
// 加载可用语音列表(部分浏览器需要异步获取)
this.synth.onvoiceschanged = () => {
this.voices = this.synth.getVoices()
}
},
methods: {
speakWord() {
if (!this.word) return
const utterance = new SpeechSynthesisUtterance(this.word)
// 设置英语发音(可调整)
utterance.voice = this.voices.find(v => v.lang.includes('en')) || null
utterance.rate = 0.8 // 语速
this.synth.speak(utterance)
},
spellWord() {
if (!this.word) return
const letters = this.word.toUpperCase().split('')
letters.forEach(letter => {
const utterance = new SpeechSynthesisUtterance(letter)
utterance.voice = this.voices.find(v => v.lang.includes('en')) || null
utterance.rate = 0.5 // 拼写时放慢速度
this.synth.speak(utterance)
})
}
}
}
</script>
关键点说明
-
语音合成检测:使用
window.speechSynthesis前建议检查浏览器支持情况,可通过以下代码判断:if (!('speechSynthesis' in window)) { alert('您的浏览器不支持语音合成API') } -
发音参数调整:

rate: 语速(0.1-10,默认1)pitch: 音高(0-2,默认1)volume: 音量(0-1,默认1)
-
跨浏览器兼容:部分浏览器(如Chrome)需要异步获取语音列表,建议在
onvoiceschanged事件中处理。
扩展功能
-
发音语言切换:

// 添加中文支持 utterance.lang = 'zh-CN' -
连续拼读控制:
// 使用队列避免语音重叠 const letterQueue = [] function processQueue() { if (letterQueue.length > 0 && !this.synth.speaking) { this.synth.speak(letterQueue.shift()) } } -
发音反馈:
utterance.onend = () => { console.log('朗读完成') }
注意事项
- 部分移动端浏览器可能限制自动播放,需要用户手势触发(如
@click) - 首次调用时可能有延迟,建议提前初始化语音引擎
- 不同操作系统提供的语音质量差异较大,可考虑第三方TTS服务作为备选方案






