Vue语音播报功能
使用Web Speech API的SpeechSynthesis接口来实现文本转语音
Web Speech API可能不在所有浏览器中都能完美支持 特别是旧浏览器
在生产环境中,你可能需要添加功能检测和后备方案。
<template><div><textarea v-model="text" placeholder="请输入文本"></textarea><button @click="speak">阅读文本</button><button @click="stop">停止阅读</button><button @click="listen">听我写</button></div>
</template><script>
export default {data() {return {text: '蜂鸟众包来新订单了 请及时接单 ',recognition: null,speech: null};},methods: {speak() {if ('speechSynthesis' in window) {const msg = new SpeechSynthesisUtterance();msg.text = this.text;// 内容msg.lang = 'zh-CN'; // 默认使用的语言:中文msg.volume = 1; // 默认声音音量:1msg.rate = 1; // 默认语速:1msg.pitch = 1; // 默认音高:1window.speechSynthesis.speak(msg)// 播放}else{alert('您的浏览器不支持语音合成');}},stop() {window.speechSynthesis.cancel();// 取消所有正在进行的语音播报},listen() {this.recognition = new webkitSpeechRecognition();this.recognition.onresult = (event) => {const text = event.results[0][0].transcript;this.text = text;};this.recognition.start();}}
};
</script>
speak-tts
npm install speak-tts
<template><div><button @click="speak">读出文本</button></div>
</template><script>
import Speech from 'speak-tts'export default {data () {return {speech:null,text:"语音播报测试 美团众包来新订单了 请及时接单 蜂鸟众包来新订单了 请及时接单",}
},
mounted(){this.speechInit();
},
methods:{speechInit(){this.speech = new Speech();this.speech.setLanguage('zh-CN');this.speech.init().then(()=>{console.log('语音播报初始化完成...')})},//语音播报speak(){this.speech.speak({text:this.text}).then(()=>{console.log("播报完成...")})}
}};
</script>