目录
Web Speech API有两个功能:用于在浏览器中实现语音识别(将人声转换为文本)和语音合成(将文本转换为人声)。简单使用介绍,详细用法再自行搜索
- var utterance = new SpeechSynthesisUtterance('Hello');
- window.speechSynthesis.speak(utterance);
- <body>
- <input id="ipt" type="text">
- <button id="btn">发音button>
- <script>
- const btn = document.getElementById('btn');
- const ipt = document.getElementById('ipt');
- btn.onclick = function(){
- const ssa = new SpeechSynthesisUtterance(ipt.value); // 或传入想要读取的字符串
- ssa.rate = 0.5; // 语速
- // ssa.volume = 0.6 // 音量
- window.speechSynthesis.speak(ssa); // 将文本添加到阅读队列
- ipt.value = '';
- }
- script>
- body>
- //创建一个SpeechRecognition对象
- const recognition = new webkitSpeechRecognition();
- //启动录音语音识别
- recognition.start();
- // 关闭录音
- recognition.stop();
- //监听语音识别结果(谷歌浏览器存在兼容问题)
- recognition.onresult = function()
- <body>
- <button id="enableIt">开始识别button>
- <button id="endRecognition">结束识别button>
- <script>
- const enableIt = document.getElementById('enableIt');
- const endRecognition = document.getElementById('endRecognition');
- //创建一个SpeechRecognition对象
- const recognition = new webkitSpeechRecognition();
- recognition.lang = 'cmn-Hans-CN'; //定义普通话 (中国大陆)
- enableIt.onclick = function(){
- //启动录音语音识别
- recognition.start();
- };
- endRecognition.onclick = function(){
- // 关闭录音
- recognition.stop();
- //监听语音识别结果(谷歌浏览器存在兼容问题)
- recognition.onresult = (event) => {
- const transcript = event.results[0][0].transcript;
- console.log(transcript); //输出语音识别结果
- }
- }
- script>
- body>