hdw
2018-10-27 ac71e34b815037f171cc73cc66553a645d1067a5
语音播报
1个文件已添加
76 ■■■■■ 已修改文件
gx_tieta/WebRoot/test-voice.html 76 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
gx_tieta/WebRoot/test-voice.html
New file
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>H5语音播报功能</title>
        <style>
            article {margin: 0 auto;max-width: 800px;text-align: center;}
            textarea {max-width: 600px;width:100%;text-align: left;}
            button{border-radius: 3px;border: 1px solid #dddddd;height: 30px;width: 80px;cursor: pointer;}
        </style>
        <link rel="stylesheet" href="src/css/layui.css">
    </head>
    <body>
        我是语音播报
    </body>
    <script type="text/javascript" src="src/layui.all.js"></script>
    <script>
        // 设置语音播报对象
        var Voice = function() {
            this.speak = window.speechSynthesis;
            this.voice = '';
            this.zh_CN = false;
            this._setLang();    // 获取并检测是否有中文的环境
        };
        // 播报语音
        Voice.prototype.play = function(txt) {
            if(!this.zh_CN) {
                if(layer) {
                    layer.msg('');
                }else {
                    alert('你的电脑不支持中文播报!');
                }
                return;
            }
            this.cancel();
            var to_speak = new SpeechSynthesisUtterance(txt);
            to_speak.voice = this.voice;    // 设定中文播报
            this.speak.speak(to_speak);
        };
        // 退出当前播报
        Voice.prototype.cancel = function() {
            this.speak.cancel();
        };
        // 检查当前语言环境
        Voice.prototype._setLang = function() {
            var _this = this;
            setTimeout(function(){
                var voices = _this.speak.getVoices();
                for(var i=0; i<voices.length; i++) {
                    var _voices = voices[0];
                    if(_voices.lang === 'zh-CN') {
                        _this.zh_CN = true;
                        _this.voice = _voices;
                    }
                }
            }, 0);
        };
        var voice = new Voice();
        setTimeout(function() {
            voice.play('我是语音播报');
        }, 3000);
    </script>
</html>