【发布时间】: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