社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
<!--
* @Author: xss 995550359@qq.com
* @Date: 2022-09-23 15:16:20
* @LastEditors: xss 995550359@qq.com
* @LastEditTime: 2022-09-23 17:41:02
* @FilePath: /打开:关闭摄像头:拍照/百度开源文字转语音tts播报.html
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="speak()">开始播报</button>
<button onclick="pause()">暂停</button>
<button onclick="resume()">播放</button>
<button onclick="cancel()">结束</button>
<select name="voice" id="voices">
<option value="">Select A Voice</option>
</select>
<button id="speak">Speak</button>
</body>
</html>
<script>
let speech = new SpeechSynthesisUtterance(); //创建文本实例
let speechSynthesis = window.speechSynthesis; //创建语音
const voicesDropdown = document.querySelector('[name="voice"]') //获取select下拉菜单
const speakButton = document.querySelector('#speak') //按钮
// 参数
speech.text = `'测试文字是对方会为空佛我家微风降温哦范围为了让 ${2}3123123阿迪分开了https://localhost/images/images/dds'`
speech.pitch = 1 // 设置话语的音调(0-2 默认1,值越大越尖锐,越低越低沉)
speech.rate = 1 // 设置说话的速度(0.1-10 默认1,值越大语速越快,越小语速越慢)
speech.volume = 10 // 设置说话的音量
speech.lang = 'zh-CN' // 设置播放语言
// 方法
speak = function () {
speechSynthesis.speak(speech)
}
pause = function () {
speechSynthesis.pause()
}
resume = function () {
speechSynthesis.resume()
}
cancel = function () {
speechSynthesis.cancel()
}
// 通过voiceschanged事件来动态获取支持的语言种类,
// 并生成options添加到html中.其中最主要的方法就是synth.getVoices()获取.
speechSynthesis.addEventListener('voiceschanged', getSupportVoices)
function getSupportVoices() {
voices = speechSynthesis.getVoices()
voices.forEach(e => {
console.log(e)
const option = document.createElement('option')
option.value = e.lang
option.text = e.lang
voicesDropdown.appendChild(option)
})
}
// 切换语言
speakButton.addEventListener('click', throttle(handleSpeak, 1000))
function handleSpeak(e) {
speech.lang = voicesDropdown.selectedOptions[0].value
speechSynthesis.speak(speech)
}
function throttle(fn, delay) {
let last = 0
return function () {
const now = new Date()
if (now - last > delay) {
fn.apply(this, arguments)
last = now
}
}
}
</script>
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!