当我尝试使用语音识别即时获取错误未捕获TypeError:recognition.addEventListener不是一个函数,我不知道为什么,我甚至复制了我所遵循的课程中的代码,但它仍然无法工作,任何提示将是apreciated。 我使用chrome(使用webkit)并使用localhost服务器和vscode的生活服务器 两个dosnt工作
class SpeechRecognition{
constructor(){}
getSpeech(){
//Assigning speech
window.SpeechRecognition = window.SpeechRecognition ||
window.webkitSpeechRecognition;
//Speech variables
const recognition = new SpeechRecognition();
recognition.interimResults = true;
recognition.lang = 'en-US';
//UI variables
let p = document.createElement('p');
const note = document.querySelector('.note');
note.appendChild(p);
recognition.addEventListener('result', e => {
})
}}
//Init
const sp = new SpeechRecognition();
sp.getSpeech();
答案 0 :(得分:0)
问题可能出在,您自定义类的命名方式与内置识别类相同。您能否尝试重命名并再次检查?另外,这是simple implementation中描述的JavaScript30 course语音识别。
// Works in Chrome and Firefox
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
// Creating new instance
const recognition = new SpeechRecognition();
recognition.interimResults = true;
recognition.lang = 'en-US';
let p = document.createElement('p');
const words = document.querySelector('.words');
words.appendChild(p);
recognition.addEventListener('result', event => {
const transcript = Array.from(event.results)
.map(result => result[0])
.map(result => result.transcript)
.join('');
// If you make a pause,
// you should probably create a new container for the next portion of recognized content
if (event.results[0].isFinal) {
p = document.createElement('p');
words.appendChild(p);
}
p.textContent = transcript;
});
// We should start recognition after each pause
// Other way it will just stop recognizing forever (till the next page load)
recognition.addEventListener('end', recognition.start);
// Starting recognition first time
recognition.start();
html {
font-size: 10px;
}
body {
background: #ffc600;
font-family: 'helvetica neue';
font-weight: 200;
font-size: 20px;
}
.words {
max-width: 500px;
margin: 50px auto;
background: white;
border-radius: 5px;
box-shadow: 10px 10px 0 rgba(0,0,0,0.1);
padding: 1rem 2rem 1rem 5rem;
background: -webkit-gradient(linear, 0 0, 0 100%, from(#d9eaf3), color-stop(4%, #fff)) 0 4px;
background-size: 100% 3rem;
position: relative;
line-height: 3rem;
}
p {
margin: 0 0 3rem;
}
.words:before {
content: '';
position: absolute;
width: 4px;
top: 0;
left: 30px;
bottom: 0;
border: 1px solid;
border-color: transparent #efe4e4;
}
<div class="words" contenteditable>
</div>
顺便说一句,您应该手动启动识别,并在每次暂停后重新启动识别,如上面的代码片段所示。
P.S。此代码将100%在Chrome 69版中正常工作。