语音识别
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList;
var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent;
const recognition = new SpeechRecognition(); // 语音识别
// 定义希望应用能够识别的语法
const colors = ['aqua', 'azure', 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral', 'crimson', 'cyan', 'fuchsia', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'indigo', 'ivory', 'khaki', 'lavender', 'lime', 'linen', 'magenta', 'maroon', 'moccasin', 'navy', 'olive', 'orange', 'orchid', 'peru', 'pink', 'plum', 'purple', 'red', 'salmon', 'sienna', 'silver', 'snow', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'white', 'yellow'];
const grammar = '#JSGF V1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;'
if (SpeechGrammarList) {
const speechRecognitionList = new SpeechGrammarList(); // 语法
speechRecognitionList.addFromString(grammar, 1); // 把语法添加到语法列表
recognition.grammars = speechRecognitionList;
}
// recognition配置
recognition.continuous = false; // 是否连续
recognition.lang = 'en-US'; // 美式英语
recognition.interimResults = false; // 是否返回临时结果
recognition.maxAlternatives = 1; // 返回需要匹配的数量值
const diagnostic = document.querySelector('.output');
const bg = document.querySelector('html');
const hints = document.querySelector('.hints');
const colorHTML = colors.map(item => '<span style="background-color:' + item + ';"> ' + item + ' </span>');
hints.innerHTML = 'Tap/click then say a color to change the background color of the app. Try ' + colorHTML.join('、') + '.';
document.body.onclick = function() {
recognition.start();
}
recognition.onresult = function(event) {
var color = event.results[0][0].transcript;
diagnostic.textContent = 'Result received: ' + color + '.';
bg.style.backgroundColor = color;
console.log('Confidence: ' + event.results[0][0].confidence);
}
recognition.onspeechend = function() {
recognition.stop();
}
recognition.onnomatch = function(event) {
diagnostic.textContent = "I didn't recognise that color.";
}
recognition.onerror = function(event) {
diagnostic.textContent = 'Error occurred in recognition: ' + event.error;
}
语音播报
const utterThis = new SpeechSynthesisUtterance();
utterThis.text = "到哪里了";
utterThis.volume = 1; // 声音的音量 范围是0到1
utterThis.rate = 0.7; //语速,数值,默认值是1,范围是0.1到10
utterThis.pitch = 1;
const play = () => {
speechSynthesis.speak(utterThis);
}