javascript - 语音识别换词
问题描述
我正在使用 SpeechRecognition,我想用表情符号替换一些口语单词。
这是我的代码:
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
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', e => {
const transcript = Array.from(e.results)
.map(result => result[0])
.map(result => result.transcript)
.join('');
const poopScript = transcript.replace(/poop|poep|poo|shit|dump/gi, '');
p.textContent = poopScript;
const unicornScript = transcript.replace(/unicorn|eenhoorn/gi, '');
p.textContent = unicornScript;
if (e.results[0].isFinal) {
p = document.createElement('p');
words.appendChild(p);
}
});
recognition.addEventListener('end', recognition.start);
recognition.start();
当您说“独角兽”时,它会打印表情符号。但是当我说便便时,它只会打印单词,而不是表情符号。如果我转动 const,它会运行 poopScript 而不是 unicornScript
const unicornScript = transcript.replace(/unicorn|eenhoorn/gi, '');
p.textContent = unicornScript;
const poopScript = transcript.replace(/poop|poep|poo|shit|dump/gi, '');
p.textContent = poopScript;
我不知道为什么它不运行我的第二个常量。
解决方案
两条replace
语句都在执行,但是你丢弃了第一个语句的结果。您需要replace
从第一个结果中调用字符串的第二个方法replace
。
var result = transcript.replace(/unicorn|eenhoorn/gi, '');
result = result.replace(/poop|poep|poo|shit|dump/gi, '');
p.textContent = result;
或者您可以将呼叫链接在一起...
p.textContent = transcript
.replace(/unicorn|eenhoorn/gi, '')
.replace(/poop|poep|poo|shit|dump/gi, '')
;