最简单的例子,在chrome上亲测有效:
const utterThis = new SpeechSynthesisUtterance('我来试试呀');
const synth = window.speechSynthesis;
synth.speak(utterThis);
加入配置,可以配置语言、音量、语速、音高,继续玩:
const utterThis = new SpeechSynthesisUtterance();
utterThis.text = '我来试试呀';
utterThis.lang = 'zh-CN'; // 语言
// syu.lang = "en-US"; //语言
utterThis.volume = 1; // 音量:0~1,默认1
utterThis.rate = 1; // 语速:0.1~10,默认1
utterThis.pitch = 1; // 音高:0~2,默认1
const synth = window.speechSynthesis;
synth.speak(utterThis);
SpeechSynthesisUtterance一些属性如下:
text – 要合成的文字内容,字符串。
lang – 使用的语言,字符串, 例如:“zh-cn”
voiceURI – 指定希望使用的声音和服务,字符串。
volume – 声音的音量,区间范围是0到1,默认是1。
rate – 语速,数值,默认值是1,范围是0.1到10,表示语速的倍数,例如2表示正常语速的两倍。
pitch – 表示说话的音高,数值,范围从0(最小)到2(最大)。默认值为1。
把代码再充实一点点:
const utterThis = new SpeechSynthesisUtterance();
utterThis.text = '我来试试呀';
utterThis.lang = 'zh-CN'; // 语言
// syu.lang = "en-US"; //语言
utterThis.volume = 1; // 音量:0~1,默认1
utterThis.rate = 1; // 语速:0.1~10,默认1
utterThis.pitch = 1; // 音高:0~2,默认1
const synth = window.speechSynthesis;
synth.speak(utterThis);