如果网页上需要文本朗读,可以直接使用javascript自带的apiSpeechSynthesisUtterance,这个api只需要简单的几行代码就可以直接朗读网页上的文本,下面是一个demo,可以直接复制看效果
源码
<!DOCTYPE html>
<htmllang="zh-CN">
<head>
<metacharset="UTF-8">
<title>网页文本转语音</title>
</head>
<body>
<h1>网页文本转语音示例</h1>
<textareaid="text"rows="5"cols="50">你好,这是一个网页文本转语音的示例。</textarea>
<br><br>
<buttononclick="speak()">播放语音</button>
<script>
functionspeak(
) {
// text的值必须是字符串 变量的话 ---- 变量+''才可以
const text = document.getElementById("text").value;
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'zh-CN'; // 设置语言为中文
utterance.rate = 1; // 语速(0.1-10)
utterance.pitch = 1; // 音调(0-2)
window.speechSynthesis.speak(utterance);
}
</script>
</body>
</html>
-
首先创建了一个
SpeechSynthesisUtterance
实例,用于定义要朗读的文本及其相关属性。 -
对
utterance
对象的属性进行设置,如text
(要朗读的文本)、lang
(语言)、rate
(语速)、volume
(音量)、pitch
(音调)等。 -
然后获取浏览器的
window.speechSynthesis
对象,它是语音合成的主要接口。 -
最后调用
synth.speak(utterance)
方法来开始朗读设置好的文本内容。
你可以根据实际需求调整 SpeechSynthesisUtterance
对象的各种属性,以获得不同的语音朗读效果
此api的官方链接:
https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance