css 如何避免新段落中出现相同的文字?

vyswwuz2  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(118)
const texts = document.querySelector(".texts");

window.SpeechRecognition =
  window.SpeechRecognition || window.webkitSpeechRecognition;

const recognition = new window.SpeechRecognition();
recognition.interimResults = true;
recognition.continuous = true;

let p = document.createElement("p");

recognition.addEventListener("result", (e) => {

  const text = Array.from(e.results)
    .map((result) => result[0])
    .map((result) => result.transcript)
    .join("");

  p.innerText = text;
  texts.appendChild(p)

  if (e.results[0].isFinal) {
    if (text.includes("hello")) {
      p = document.createElement("p");
      p.classList.add("replay");
      p.innerText = "Hi";
      texts.appendChild(p);
    }

    p = document.createElement("p");
  } 

  console.log(e);
});

recognition.addEventListener("end", () => {
  recognition.start();
});

recognition.start();

字符串
每当我在开头说“hello”* 时,“hello”总是会出现在我的下一段。
如何解决这个问题?
我希望您可以在不添加第三方软件包的情况下解决此问题。我需要逻辑。如果您需要,请填写说明。

juud5qan

juud5qan1#

导致重复“hello”的问题是由于连续事件侦听器。当recognition.continuous属性设置为true时,即使处理完结果,识别也会继续运行,从而导致重复的“hello”文本。
要解决此问题,您可以在收到最终结果时停止识别,然后重新启动。这样,识别将重置,您将不会遇到重复的“你好”问题。
您的更新代码:

const texts = document.querySelector(".texts");

window.SpeechRecognition =
  window.SpeechRecognition || window.webkitSpeechRecognition;

const recognition = new window.SpeechRecognition();
recognition.interimResults = true;
recognition.continuous = true;

recognition.addEventListener("result", (e) => {
  const text = Array.from(e.results)
    .map((result) => result[0])
    .map((result) => result.transcript)
    .join("");

  // Check if the text contains "hello" and add a response
  if (text.includes("hello")) {
    const responseP = document.createElement("p");
    responseP.classList.add("replay");
    responseP.innerText = "Hi";
    texts.appendChild(responseP);
  }

  // Clear the previous content in texts
  texts.innerHTML = "";

  // Create a new paragraph element for the current result
  const p = document.createElement("p");
  p.innerText = text;
  texts.appendChild(p);

  if (e.results[0].isFinal) {
    // Stop and restart the recognition when a final result is received
    recognition.stop();
    recognition.start();
  }
});

recognition.addEventListener("end", () => {
  // If the recognition ends, restart it to keep listening
  recognition.start();
});

recognition.start();

字符串

相关问题