提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

继扫码功能之后,新增加语音播报功能

客户提出问题:扫码后不知道有没有扫上,没有提示,希望加上语音提示,想要有个报数功能,扫了多少个就报一下数


一、实现方式

使用的是“Web Speech API”的方式,Web Speech API允许网页应用与用户的语音输入和输出设备交互。可以使用这个API来实现语音播报

二、使用步骤

1.创建语音合成对象

const speech = new SpeechSynthesisUtterance()

2.设置语音内容

speech.text = '这是需要播报的内容';

封装后可将语音内容作为参数传到函数中

3.设置语音属性(可选)

speech.lang = 'zh-CN'; // 设置语言为中文
speech.volume = 1;     // 设置音量
speech.rate = 1;       // 设置语速
speech.pitch = 1;      // 设置音高

根据自身需求设置语音属性

4.开始播报

window.speechSynthesis.speak(speech);

5.页面组件使用(封装函数)

在methods中封装speak函数,将播报内容和语音属性作为参数传入,在需要语音播报的地方调用函数即可

methods: {
    speak(content, attr) {
      if ('speechSynthesis' in window) {
        const speech = new SpeechSynthesisUtterance(content.toString());
        speech.lang = attr.lang || 'zh-CN'; // 设置语言为中文
		speech.volume = attr.volume || 1;     // 设置音量
		speech.rate = attr.rate || 1;       // 设置语速
		speech.pitch = attr.pitch || 1;      // 设置音高
        // 监听开始播报
        speech.onstart = () => {
        };
        // 监听结束播报
        speech.onend = () => {
        };
        // 监听播报异常
        speech.onerror = () => {
        };
        window.speechSynthesis.speak(speech);
      } else {
        alert('您的浏览器不支持语音合成功能');
      }
    },

	// 调用语音播报函数
	callSpeakFunc() {
		let content = "需要播报的内容"
		let speakAttr = {
			lang: 'zh-CN',
			volume: 1,
			rate: 1,
			pitch: 1,
		}
		this.speak(content, speakAttr)
	}
   }

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐