语音播报功能开发

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 一、实现网页版本的语音自动播放功能,不适用移动端
  • 二、实现移动端的语音播报功能
  • 总结


一、实现网页版本的语音自动播放功能,不适用移动端

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <title>Document</title>
    <script type="text/javascript">
        var speaker = new window.SpeechSynthesisUtterance();
        var speakTimer,
            stopTimer;
        // 开始朗读
        function speakText() {
            var context = document.getElementById('ttsText');
            clearTimeout(speakTimer);
            window.speechSynthesis.cancel();
            speakTimer = setTimeout(function () {
                speaker.volume = 0.9
                speaker.text = context.innerHTML;
                window.speechSynthesis.speak(speaker);
            }, 200);
        }
        // 停止朗读
        function stopSpeak() {
            clearTimeout(stopTimer);
            clearTimeout(speakTimer);
            stopTimer = setTimeout(function () {
                window.speechSynthesis.cancel();
            }, 20);
        }
    </script>
</head>

<body>
    <p id="ttsText">
        蟠龙会议室有订单信息,请注意查看
    </p>
    <div>
        <input type="button" id="start_btn" onclick="speakText()" value="播放">
        <input type="button" id="cancel_btn" onclick="stopSpeak()" value="取消">
    </div>
</body>
</html>

二、实现移动端的语音播报功能

uni.getSystemInfo({
	success: function (res) {
		console.log(res)
	}
});

var innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = false; //不自动播放
innerAudioContext.src = '';

var _this = this;
innerAudioContext.src = 'https://500.kzt.icu/index/tingzhi.mp3';
innerAudioContext.play(); //直接播放
innerAudioContext.onPlay(function() { //暂停之后点击播放继续播放
	// uni.showToast({
	// 	title: '播报中...',
	// 	icon: 'none',
	// 	duration:100
	// })
	if (_this.currentTime) {
		innerAudioContext.seek(_this.currentTime)
	}
})

总结

人生物语:人生的进步,靠的是失败。感情的进步,靠的是失恋。所以,每一个伤害过你的人,都是你的老师。不需要感谢,但请务必牢记。

你可能感兴趣的:(javascript)