SpeechSynthesisUtterance 语音合成使用

SpeechSynthesisUtterance基本属性方法

  1. SpeechSynthesisUtterance.lang 获取并设置话语的语言
  2. SpeechSynthesisUtterance.pitch 获取并设置话语的音调(值越大越尖锐,越低越低沉)
  3. SpeechSynthesisUtterance.rate 获取并设置说话的速度(值越大语速越快,越小语速越慢)
  4. SpeechSynthesisUtterance.text 获取并设置说话时的文本
  5. SpeechSynthesisUtterance.voice 获取并设置说话的声音
  6. SpeechSynthesisUtterance.volume 获取并设置说话的音量
  7. SpeechSynthesisUtterance.text基本方法

使用方法

  • speak() 将对应的实例添加到语音队列中
  • cancel() 删除队列中所有的语音.如果正在播放,则直接停止
  • pause() 暂停语音
  • resume() 恢复暂停的语音
  • getVoices 获取支持的语言数组. 注意:必须添加在voiceschanged事件中才能生效

创建一个类:

class Voices {
    constructor(text,isPlay) {
        this.synth       = window.speechSynthesis;
        this.msg         = new SpeechSynthesisUtterance(text);
        this.msg.text    = text;     // 文字内容
        this.msg.lang    = "zh-CN";  // 使用的语言:中文
        this.msg.volume  = 100;      // 声音音量:1
        this.msg.rate    = 0.75;     // 语速:1
        this.msg.pitch   = 10;       // 音高:1
        this.isPlay      = isPlay;
        //获取声音列表并设置声音
        this.synth.addEventListener('voiceschanged',()=>{
            this.msg.voice = this.synth.getVoices()[0];//语种
            console.log(this.msg.voice)
        });
        
    }
    play(){
        setTimeout(() => {
            speechSynthesis.speak(this.msg);
        }, 500);
    }

}

调用该方法:

<script type="text/javascript" charset="utf-8" src="./Voices.js"></script>
<script type="text/javascript" charset="utf-8">

 
 window.onload = ()=>{
     let res = new Voices('测试语音',true);
     res.play();
 }

注意:如果谷歌版本太高,只有触发点击事件才有效哦

已经测试完毕~

 

作者:Carver-大脸猫

出处:https://www.cnblogs.com/carver/articles/16890225.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

转载请注明原处

posted @   Carver-大脸猫  阅读(953)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up light_mode palette
选择主题