H5
https://blog.csdn.net/qq_35185288/article/details/106281628
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name= "viewport"content="width=device-width, initial-scale=1.0">
<title>公众号:霸道的程序猿</title>
</head>
<body>
<h1>公众号:霸道的程序猿</h1>
<input id="btn1" type="button" value ="点我" onclick="test();"/>
</body>
</html>
<script>
function test()
{
const sos = `公众号:霸道的程序猿`;
const synth = window.speechSynthesis;
let msg = new SpeechSynthesisUtterance(sos);
synth.speak(msg)
}
</script>
1.先new,把SpeechSynthesisUtterance nuw出来
let a=new SpeechSynthesisUtterance();
2.设置属性
a.lang="zh"; 设置说中文说英文
a.pitch=数字; 设置音调(里面的数越大,声音就越尖锐)
a.rate=数字; 设置语速(里面的数越大,语速就越快)
a.text="; 你要说的话"
a.voice=数字; 设置谁说话(里面有男声有女声)
a.volume=数字; 设置音量的大小
3.调用 speechSynthesis.下面的方法
speak(a) 将这句话输出(播放,但要等前面那句话说完)
cancel(a) 直接删除当前播放
pause() 暂停语音
resume() 恢复暂停的语音
https://blog.csdn.net/qq_65705539/article/details/127780708
WEB
https://blog.csdn.net/weixin_44240581/article/details/126394648
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="">
<input type="text" class="txt" >
<label for="rate">语音速度</label><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate">
<label for="pitch">音调</label><input type="range" min="0" max="2" value="1" step="0.1" id="pitch">
<button type="submit">文字转语音</button>
</form>
<select></select>
</body>
</html>
<script>
const voiceSelect = document.querySelector('select');
const rate = document.querySelector('#rate');
const pitch = document.querySelector('#pitch');
let voices = [];
const synth = window.speechSynthesis;
synth.addEventListener('voiceschanged', () => {
voices = synth.getVoices();
for (let i = 0; i < voices.length ; i++) {
const option = document.createElement('option');
option.textContent = `${voices[i].name} (${voices[i].lang})`;
if (voices[i].default) {
option.textContent += ' — DEFAULT';
}
option.setAttribute('data-lang', voices[i].lang);
option.setAttribute('data-name', voices[i].name);
voiceSelect.appendChild(option);
}
});
document.querySelector('form').onsubmit = function (e) {
e.preventDefault();
const word = document.querySelector('.txt').value;
let utterThis = new SpeechSynthesisUtterance(word);
const selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for (let i = 0; i < voices.length ; i++) {
if (voices[i].name === selectedOption) {
utterThis.voice = voices[i];
}
}
utterThis.pitch = pitch.value;
utterThis.rate = rate.value;
synth.speak(utterThis);
}
// synth.pending 同时播放两条语音,第一条在播放,第二条则在队列中,返回true
// synth.speaking 是否有语音在播放
// synth.resume 置于非暂停状态
</script>
文档更新时间: 2023-11-16 06:24 作者:admin