SpeechSynthesis 15 秒后停止说话

问题描述 投票:0回答:1

我是一名前端开发人员,我在使用 React 中的 SpeechSynthesis API 时遇到了一些麻烦。

问题是我需要重现许多文本,而这些文本可能会很长,所以我所做的是将文本分成大约 150 个字符的块。这似乎解决了问题,但最近我发现了这个API的其他限制,因为它只读取15秒,然后就停止了。

在网上我找到了很多解决方案,但所有这些似乎都不再起作用了,比如超时14秒或更短,调用方法

resume()
。所以我想知道你们中是否有人已经遇到过这个问题或以某种方式解决了它。

今天我添加了这个可能的解决方案,它实际上有效,但它在数组的每个元素之间造成了明显的暂停。

let readingText = ["all of my strings", "", ""]; //This contains chunks of the same sentence
const synthesis = speechSynthesis;

readingText.forEach((text, index) => {
    console.log(index, text)
    let utterance = new SpeechSynthesisUtterance(text);
    this.speechSynthesisConfig(utterance);
    synthesis.speak(utterance);
})

提前非常感谢

javascript reactjs google-chrome speech-synthesis
1个回答
0
投票

我在为聊天机器人构建语音消息时遇到了同样的问题。

这个解决方案非常适合我。

注意:在调用下一个块之前取消语音合成,以确保其播放流畅。

function makeCunksOfText (text){
    const maxLength = 190;
  let speechChunks = [];

  // Split the text into chunks of maximum length maxLength without breaking words
  while (text.length > 0) {
    if (text.length <= maxLength) {
      speechChunks.push(text);
      break;
    }

    let chunk = text.substring(0, maxLength + 1);
    
    let lastSpaceIndex = chunk.lastIndexOf(' ');
    if (lastSpaceIndex !== -1) {
      speechChunks.push(text.substring(0, lastSpaceIndex));
      text = text.substring(lastSpaceIndex + 1);

    } else {
      // If there are no spaces in the chunk, split at the maxLength
      speechChunks.push(text.substring(0, maxLength));
      text = text.substring(maxLength);
    }
  }

return speechChunks
}


async function speakText (text){
  const speechChunks = makeCunksOfText(text)
    for (let i = 0; i < speechChunks.length; i++) {
    await new Promise((resolve, reject) => {
      window.speechSynthesis.cancel();
      let speech = new SpeechSynthesisUtterance(speechChunks[i]);
      speech.rate = 0.8;
      speech.voice = window.speechSynthesis
        .getVoices()
        .find(voice => voice.name === "Google US English");
      window.speechSynthesis.speak(speech);
      speech.onend = () => {
        resolve();
      };
      speech.onerror = (error) => {
        resolve();
      };
    });
  }
  
}


async function run () {

await speakText(document.querySelector('#text').value)
}
<input id="text" type="text" placeholder="add Text here" value="That's great to know For beginners, I recommend starting with basic grammar and vocabulary exercises, practicing listening and speaking with simple conversations, and gradually increasing the complexity of your activities. There are many online resources and language learning apps available to help you with your journey. Do you have any specific areas you'd like to focus on or any resources you're interested in?"  /> <button onclick="run()"> Play </button>

© www.soinside.com 2019 - 2024. All rights reserved.