【问题标题】:Change speechSynthesis voice with SpeechRecognition使用 SpeechRecognition 更改语音合成语音
【发布时间】:2023-10-14 16:36:02
【问题描述】:

我正在通过麦克风使用 SpeechRecognition,并通过 SpeechSynthesis 将数据转发给我。

我在页面加载时将声音设置为女性声音,并希望能够通过说“男性声音”切换为男性声音,然后转播“我现在是男性”。我后来也希望能够做相反的事情 - 当它设置为男性声音时,说“女性声音”然后它会切换回来。

我目前可以这样做,但男声只会说一次,因为声音没有被保存,只是作为参数传递。因此,接下来所说的将回到女声:

let voices = [];
window.speechSynthesis.onvoiceschanged = function() {
  voices = window.speechSynthesis.getVoices();
};

function loadVoices(message, voice) {
  const msg = new SpeechSynthesisUtterance();
  msg.voice = voice || voices[48]; // female voice
  msg.text = message;
  speechSynthesis.speak(msg);
};

// asking for voice change here
  if (transcript.includes('male voice')) {
    let message = ('I am now a man');
    let voice = voices[50]; // male voice
    loadVoices(message, voice);
  }

我尝试使用一个全局变量,使msg.voice 指向一个全局变量,但这不起作用,而且语音恢复为默认值(电子语音):

let voiceGender = voices[48];
function loadVoices(message) {
  const msg = new SpeechSynthesisUtterance();
  msg.voice = voiceGender // now a variable pointing to another.
  msg.text = message;
  speechSynthesis.speak(msg);
};

  if (transcript.includes('male voice')) {
    let message = ('I am now a man');
    let voiceGender = voices[50]; // changing the global variable
    loadVoices(message);
  }

如果我在loadVoices() 内声明voiceGender,那么我无法从另一个函数内的if 更改它。

如何设置 Javascript 结构以实现此目的?

【问题讨论】:

    标签: javascript speech-recognition voice speech-synthesis


    【解决方案1】:

    我通过在 loadVoices 函数中添加一个函数和一个带有条件的布尔值来解决它:

    // on pageload the voice is set to a female voice
    let femaleVoice = true;
    
    function loadVoices(message) {
      const msg = new SpeechSynthesisUtterance();
    
      // checks the boolean
      if (femaleVoice) {
        msg.voice = voices[48];
      } else {
        msg.voice = voices[50];
      }
    
      msg.text = message;
      speechSynthesis.speak(msg);
    };
    
    // changes the boolean / changes the gender of the SpeechSynthesisUtterance voice
    function changeVoice() {
      if (femaleVoice) {
        femaleVoice = false;
      } else {
        femaleVoice = true;
      }
    }
    
    if (transcript.includes('male voice') || transcript.includes('female voice') ) {
      // calls the function to change the boolean.
      changeVoice();
    
      let message = ('I now have a different voice');
      loadVoices(message);
    }
    

    它确实添加了比最初想要的多一点的行,但绝对有效。

    【讨论】: