当前位置: 首页 > 工具软件 > speak.js > 使用案例 >

基于JavaScript语音播报功能展示

冯和硕
2023-12-01

1、首先定义播报方法

可以把这个方法写在一个js文件里面,例如定义一个js文件名称为:Speech.js,文件内容如下:

"use strict";
var isLoading = false;
var VoiceReader = function () {
    var VoiceReader = function VoiceReader(readWords, readButtonId) {
        return new VoiceReader.fn.init(readWords, readButtonId);
    };

    VoiceReader.fn = VoiceReader.prototype = {
        constructor: VoiceReader,
        init: function init(readWords, callback, eachcallback, readButtonId) {
            VoiceReader.readWords = readWords;
            VoiceReader.inited = 0;
            //VoiceReader.voiceObj = null;
            this.read = function (callback, eachcallback) {
                VoiceReader.fn.stop();
                VoiceReader.readIndex = 0;
                VoiceReader.isStoped = 0;
                VoiceReader.sayutil = null;
                VoiceReader.callback = callback;
                VoiceReader.eachcallback = eachcallback;
                VoiceReader.buttonid = readButtonId;
                this.readVoice();
            };
        },
        callback: function callback() {
            
        },
        eachcallback: function eachcallback(i) {
            
        },
        readVoice: function readVoice() {
            var currentBrowser = GetCurrentBrowser();
            switch (currentBrowser) {
                case "Chrome":
                case "FF":
                case "Opera":
                case "Safari":
                    if (VoiceReader.isStoped == 0) {
                        VoiceReader.sayutil = new window.SpeechSynthesisUtterance(VoiceReader.readWords[VoiceReader.readIndex]);
                        //播报结束事件
                        VoiceReader.sayutil.onend = function (callback) {
                            VoiceReader.readIndex++;
                            if (VoiceReader.readWords.length > VoiceReader.readIndex - 1) {
                                if (typeof VoiceReader.eachcallback == "function") {
                                    VoiceReader.eachcallback(VoiceReader.readIndex - 1);
                                }
                                VoiceReader.fn.readVoice();
                            } else {
                                VoiceReader.readIndex = 0;
                                VoiceReader.isStoped = 1; //播放停止
                                isLoading = false;
                                if (typeof VoiceReader.callback == "function") {
                                    VoiceReader.callback();
                                }
                            }
                        };
                        window.speechSynthesis.speak(VoiceReader.sayutil);
                    };
                    break;
                case "IE55":
                case "IE6":
                case "IE7":
                case "IE8":
                case "IE9":
                case "IE10":
                case "IE11":
                    if (VoiceReader.isStoped == 0) {
                        if (VoiceReader.inited == 0) {
                            try {
                                loadScriptString("VoiceReader.voiceObj = new ActiveXObject('Sapi.SpVoice');"); //此对象需要在单独的script对象中定义,方可动态绑定事件
                                //播报结束事件
                                var endFunc = function endFunc() {
                                    VoiceReader.readIndex++;
                                    if (VoiceReader.isStoped == 1) {
                                        VoiceReader.readIndex = 0;
                                    }
                                    if (VoiceReader.readWords.length > VoiceReader.readIndex - 1) {
                                        if (typeof VoiceReader.eachcallback == "function") {
                                            VoiceReader.eachcallback(VoiceReader.readIndex - 1);
                                        }
                                        VoiceReader.fn.readVoice();
                                    } else {
                                        VoiceReader.readIndex = 0;
                                        VoiceReader.isStoped = 1; //播放停止
                                        isLoading = false;
                                        if (typeof VoiceReader.callback == "function") {
                                            VoiceReader.callback();
                                        }
                                    }
                                };
                                var startFunc = function startFunc() { };
                                var voiceScript = "function VoiceReader.voiceObj::EndStream(){" + endFunc.toString().match(/(?:\/\*[\s\S]*?\*\/|\/\/.*?\r?\n|[^{])+\{([\s\S]*)\}$/)[1] + "}";
                                voiceScript += "function VoiceReader.voiceObj::StartStream(){" + startFunc.toString().match(/(?:\/\*[\s\S]*?\*\/|\/\/.*?\r?\n|[^{])+\{([\s\S]*)\}$/)[1] + "}";
                                loadScriptString(voiceScript);
                                VoiceReader.inited = 1;
                            } catch (e) {
                                alert("ActiveXObject没有安装,请在IE选项中修改相应设置!请设置该浏览器:Internet选项->安全->自定义级别->对标记为可安全执行脚本ActiveX控件执行脚本 该项设置启用! " + e.message);
                                isLoading = false;
                                if (typeof VoiceReader.callback == "function") {
                                    VoiceReader.callback();
                                }
                            }

                        }
                       
                        if (VoiceReader.voiceObj) {
                            VoiceReader.voiceObj.Resume();
                            VoiceReader.voiceObj.Speak(VoiceReader.readWords[VoiceReader.readIndex], 1);
                        } else {
                            alert("ActiveXObject没有安装,请在IE选项中修改相应设置!请设置该浏览器:Internet选项->安全->自定义级别->对标记为可安全执行脚本ActiveX控件执行脚本 该项设置启用! ");
                            isLoading = false;
                            if (typeof VoiceReader.callback == "function") {
                                VoiceReader.callback();
                            }
                        }
                    }
                    break;
            }
        },
        stop: function stop(callback) {
            var currentBrowser = GetCurrentBrowser();
            switch (currentBrowser) {
                case "Chrome":
                case "FF":
                case "Opera":
                case "Safari":
                    window.speechSynthesis.cancel();
                    VoiceReader.readIndex = 0;
                    VoiceReader.isStoped = 1;
                    break;
                case "IE55":
                case "IE6":
                case "IE7":
                case "IE8":
                case "IE9":
                case "IE10":
                case "IE11":
                    if (VoiceReader.inited == 1) {
                        if (VoiceReader.voiceObj) {
                            VoiceReader.isStoped = 1;
                            VoiceReader.voiceObj.Speak("", 2);
                            VoiceReader.readIndex = 0;
                        }
                    }
                    break;
            }
            if (typeof callback == "function") {
                callback();
            }
        },
        pause: function pause(callback) {
            var currentBrowser = GetCurrentBrowser();
            switch (currentBrowser) {
                case "Chrome":
                case "FF":
                case "Opera":
                case "Safari":
                    window.speechSynthesis.pause();
                    break;
                case "IE55":
                case "IE6":
                case "IE7":
                case "IE8":
                case "IE9":
                case "IE10":
                case "IE11":
                    if (VoiceReader.voiceObj) {
                        //VoiceReader.isStoped = 1;
                        VoiceReader.voiceObj.Pause();
                    }
                    break;
            }
            if (typeof callback == "function") {
                callback();
            }
        },
        resume: function resume(callback) {
            var currentBrowser = GetCurrentBrowser();
            switch (currentBrowser) {
                case "Chrome":
                case "FF":
                case "Opera":
                case "Safari":
                    window.speechSynthesis.resume();
                    window.speechSynthesis.resume();
                    break;
                case "IE55":
                case "IE6":
                case "IE7":
                case "IE8":
                case "IE9":
                case "IE10":
                case "IE11":
                    if (VoiceReader.voiceObj) {
                        //VoiceReader.isStoped = 0;
                        VoiceReader.voiceObj.Resume();
                    }
                    break;
            }
            if (typeof callback == "function") {
                callback();
            }
        }
    };

    VoiceReader.fn.init.prototype = VoiceReader.fn;
    return VoiceReader;
} ();

//添加jscode
function loadScriptString(code) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    try {
        script.appendChild(document.createTextNode(code));
    } catch (ex) {
        script.text = code;
    }
    document.body.appendChild(script);
}

//获取当前浏览器类型
//myBrowser() start
function GetCurrentBrowser() {
    //取得浏览器的userAgent字符串
    var userAgent = navigator.userAgent.toLocaleLowerCase();
    var isChrome = userAgent.indexOf("chrome") > -1; //判断是否谷歌浏览器
    var isOpera = userAgent.indexOf("opera") > -1; //判断是否Opera浏览器
    var isIE = userAgent.match(/msie/) != null || userAgent.match(/trident/) != null; //userAgent.indexOf("compatible") > -1 && userAgent.indexOf("msie") > -1 && !isOpera; //判断是否IE浏览器
    var isFF = userAgent.indexOf("firefox") > -1; //判断是否Firefox浏览器
    var isSafari = userAgent.indexOf("safari") > -1; //判断是否Safari浏览器	
    if (isIE) {
        var IE5, IE55, IE6, IE7, IE8, IE9, IE10, IE11;
        IE5 = IE55 = IE6 = IE7 = IE8 = IE9 = IE10 = IE11 = false;
        /*
        var reIE = new RegExp("msie (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        */
        var fIEVersion = userAgent.match(/msie ([\d.]+)/) != null ? userAgent.match(/msie ([\d.]+)/)[1] : userAgent.match(/rv:([\d.]+)/)[1];
        IE55 = fIEVersion == 5.5;
        IE6 = fIEVersion == 6.0;
        IE7 = fIEVersion == 7.0;
        IE8 = fIEVersion == 8.0;
        IE9 = fIEVersion == 9.0;
        IE10 = fIEVersion == 10.0;
        IE11 = fIEVersion == 11.0;
        if (IE55) {
            return "IE55";
        }
        if (IE6) {
            return "IE6";
        }
        if (IE7) {
            return "IE7";
        }
        if (IE8) {
            return "IE8";
        }
        if (IE9) {
            return "IE9";
        }
        if (IE10) {
            return "IE10";
        }
        if (IE11) {
            return "IE11";
        }
    } //isIE end
    if (isFF) {
        return "FF";
    }
    if (isOpera) {
        return "Opera";
    }
    if (isChrome) {
        return "Chrome";
    }
} //myBrowser() end

 2、调用播报事件

根据实际的业务需求来获取播报的内容信息。 

<script type="text/javascript" charset="utf-8" src='@Url.Content("~/Scripts/jquery.min.js")'> </script>
<script type="text/javascript" charset="utf-8" src='@Url.Content("~/Scripts/Speech.js")'> </script>

<div>
<button type="button" onclick="GetVoiceSpeech()">
                    播报</button>
                <button type="button" onclick="GetVoiceSpeechPause()">
                    播报暂停</button>
                <button type="button" onclick="GetVoiceSpeechResume()">
                    播报继续</button>
                <button type="button" onclick="GetVoiceSpeechStop()">
                    播报停止</button>
</div>

<script type="text/javascript">
    var readStrArr = [];
    var reader = null;
    var readIndex = 0;
    "use strict";
    //开始播报
    function GetVoiceSpeech() {
        if (isLoading) return;
        isLoading = true;
        $.ajax({
            type: 'post',
            url: "url",
            dataType: "json",
            data: {},
            cache: false,
            success: function (json) {
                for (var i = 0; i < json.list.length; i++) {
                    readStrArr.push(json.list[i].name + "  ");
                }
                reader = VoiceReader(readStrArr, "");
                reader.read(function () {
                }, function (i) {
                });
                readStrArr = [];
            },
            error: function (e) {
                isLoading = false;
            }
        });

    }
    //暂停播报
    function GetVoiceSpeechPause() {
        reader.pause(function () {
        });
    }
    //继续播报
    function GetVoiceSpeechResume() {
        reader.resume(function () {
        });
    }
    //停止播报
    function GetVoiceSpeechStop() {
        reader.stop(function () {
            isLoading = false;
        });
    }
</script>



//以下是测试内容,供参考
<div>
<button type="button" onclick="GetVoiceSpeechTest()">
                    播报</button>
                <button type="button" onclick="GetVoiceSpeechPauseTest()">
                    播报暂停</button>
                <button type="button" onclick="GetVoiceSpeechResumeTest()">
                    播报继续</button>
                <button type="button" onclick="GetVoiceSpeechStopTest()">
                    播报停止</button>
</div>

<script type="text/javascript">
    var readStrArr = [];
    readStrArr.push("我是张三 大家好");
    readStrArr.push("我是李四 大家好");
    readStrArr.push("我是王五 大家好,欢迎来我校");
    var reader = null;
    var readIndex = 0;
    "use strict";
    //开始播报
    function GetVoiceSpeechTest() {
        if (isLoading) return;
        reader.read(function () {}, function (i) {});
        readStrArr = [];
    }
    //暂停播报
    function GetVoiceSpeechPauseTest() {
        reader.pause(function () {
        });
    }
    //继续播报
    function GetVoiceSpeechResumeTest() {
        reader.resume(function () {
        });
    }
    //停止播报
    function GetVoiceSpeechStopTest() {
        reader.stop(function () {
            isLoading = false;
        });
    }
</script>





 

 类似资料: