我正在使用SpeechRecognition和麦克风,并使用speechSynthesis将数据传回给我。
我在页面加载时使声音成为女性声音,并希望能够通过说出“男性声音”来切换到男性声音,然后传达“我现在是男人”。我后来也希望能够做相反的事情 - 当它设置为男性声音时,说“女性声音”并且它会切换回来。
我现在可以这样做,但男声只会说一次,因为声音没有被保存,只作为一个参数传递。因此,接下来说的话就会回到女声:
recyclerView.setNestedScrollingEnabled(false);
我尝试使用全局变量,使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);
}
内声明voiceGender
,那么我无法从另一个函数中的loadVoices()
更改它。
如何设置Javascript结构以便实现此目的?
答案 0 :(得分: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);
}
它确实添加了比原先想要的更多的线条,但绝对有效。