使用 SpeechRecognition 改变 speechSynthesis 的声音

Change speechSynthesis voice with SpeechRecognition

我在麦克风上使用 SpeechRecognition,并通过 speechSynthesis 将数据传回给我。

我在页面加载时将声音设置为女声,并希望能够通过说 "male voice" 切换为男声,然后将中继 "I am now a man"。我稍后还希望能够做相反的事情 - 当它设置为男性声音时,说 "female voice" 然后它切换回来。

我目前可以这样做,但男性声音只会说一次,因为声音不会被保存,只会作为参数传递。所以,接下来说的就是女声了:

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 结构来实现这一点?

我通过在 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);
}

它确实比最初想要的多了一点点但确实有效。