123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- // 定义 SpeakVoice 类并将其导出为默认导出
- export default class SpeakVoice {
- synth: SpeechSynthesis;
- instance: any;
- voices: { name: string }[];
- constructor() {
- this.synth = window.speechSynthesis; // 启用文本
- this.instance = new SpeechSynthesisUtterance();
- this.voices = [];
- this.initVoice();
- }
- // 初始化
- initVoice() {
- this.instance.volume = 1; // 声音音量:1,范围从0到1
- this.instance.rate = 3; // 设置语速:1,范围从0到100
- this.instance.lang = 'zh-CN'; // 使用的语言:中文
- this.instance.localService = true;
- this.instance.pitch = 0; // 表示说话的音高,数值,范围从0(最小)到2(最大)。默认值为1
- this.instance.voiceURI = 'Ting-Ting';
- // this.instance.voiceURI = 'Google 普通话(中国大陆)';
- }
- // 语音开始
- handleSpeak() {
- this.synth.speak(this.instance as SpeechSynthesisUtterance); // 播放
- }
- // 语音队列重播
- handleReply(text) {
- this.instance.text = text;
- this.handleCancel();
- this.handleSpeak();
- }
- // 语音队列删除 , 删除队列中所有的语音.如果正在播放,则直接停止
- handleCancel() {
- this.synth.cancel();
- }
- // 语音暂停, 暂停语音该次语音播放
- handleStop() {
- this.synth.pause();
- }
- // 恢复暂停的语音
- handleResume() {
- this.synth.resume();
- }
- // 声音切换
- setVoiceType(voiceName) {
- const voice = this.voices.find((voice) => voice.name === voiceName);
- if (voice) {
- this.instance.voice = voice;
- } else {
- console.warn('指定的语音未找到:', voiceName);
- }
- }
- // 获取可用的中文语音
- async getSpeechCnVoices() {
- try {
- const voices = await this.getSpeechVoices();
- const cnVoices = voices.filter((item) => item.lang.startsWith('zh-') && item.localService);
- if (cnVoices.length === 0) {
- throw new Error('没有可用的中文语音!');
- }
- this.voices = cnVoices;
- return cnVoices;
- } catch (error) {
- console.error(error);
- throw error;
- }
- }
- // 异步获取所有可用的语音
- async getSpeechVoices() {
- // 返回一个新的 Promise
- return new Promise((resolve) => {
- // 如果当前没有可用的语音,等待 onvoiceschanged 事件触发
- if (this.synth.getVoices().length === 0) {
- this.synth.onvoiceschanged = () => resolve(this.synth.getVoices());
- } else {
- // 如果已经有可用的语音,立即解析 Promise
- resolve(this.synth.getVoices());
- }
- });
- }
- }
|