语音识别词替换

时间:2021-06-08 19:34:01

标签: javascript constants speech-recognition

我正在使用语音识别,我想用表情符号替换一些口语。

这是我的代码:

    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;

我不知道为什么它不运行我的第二个常量。

1 个答案:

答案 0 :(得分:0)

两个 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, '?')
       ;