ThirdParty
2019-04-24 17:36:15 +08:00
我再来一个 H5 语音转文字 和 文字转语音, 是 w3c 定义的标准,由浏览器实现
```
<form action="">
<input type="text" />
<select>
</select>
<input type="submit" />
</form>
<div class="output"></div>
<script>
window.onload = function () {
// var grammar = '#JSGF V1.0; grammar colors; public <color> = 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 ;'
// //var recognition = new SpeechRecognition();
// var recognition = new webkitSpeechRecognition();
// //var speechRecognitionList = new SpeechGrammarList();
// var speechRecognitionList = new webkitSpeechGrammarList();
// speechRecognitionList.addFromString(grammar, 1);
// recognition.grammars = speechRecognitionList;
// //recognition.continuous = false;
// recognition.lang = 'en-US';
// recognition.interimResults = false;
// recognition.maxAlternatives = 1;
// var diagnostic = document.querySelector('.output');
// var bg = document.querySelector('html');
// document.body.onclick = function () {
// recognition.start();
// console.log('Ready to receive a color command.');
// }
// recognition.onresult = function (event) {
// var color = event.results[0][0].transcript;
// diagnostic.textContent = 'Result received: ' + color;
// bg.style.backgroundColor = color;
// }
var synth = window.speechSynthesis;
var inputForm = document.querySelector('form');
var inputTxt = document.querySelector('input');
var voiceSelect = document.querySelector('select');
function populateVoiceList() {
voices = synth.getVoices();
for (i = 0; i < voices.length; i++) {
var option = document.createElement('option');
option.textContent = voices[i].name + ' [' + voices[i].lang + '] ';
if (voices[i].default) {
option.textContent += ' DEFAULT';
}
option.setAttribute('data-lang', voices[i].lang);
option.setAttribute('data-name', voices[i].name);
voiceSelect.appendChild(option);
}
}
populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
inputForm.onsubmit = function (event) {
event.preventDefault();
var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for (i = 0; i < voices.length; i++) {
if (voices[i].name === selectedOption) {
utterThis.voice = voices[i];
}
}
synth.speak(utterThis);
inputTxt.blur();
}
};
</script>
```