【笔记】通过JS朗读文本内容

前言

通过JS朗读文本内容

正文

  • 修改39~57行,在msg.text中定义朗读内容

本案例针对Hexo博客进行优化,自动获取博客正文内容作为朗读内容,在其他场景下请修改msg.text的值作为朗读内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>

<button onclick="speak()">朗读开/关</button>

<div class="post-body">
<h1>文本内容</h1>
<p>文本内容</p>
</div>

<script>
// 朗读者对象
let synth = undefined;
const msg = new SpeechSynthesisUtterance();
// 切换朗读者开关
function speak() {
// 判断是否支持
if (!window.speechSynthesis) {
console.log("不支持");
return;
} else {
console.log("支持");
}

// 判断是否已创建朗读者对象,如果undefined就创建朗读者对象,如果已创建对象就销毁
if (synth === undefined) {
// 创建朗读者对象
synth = window.speechSynthesis;
// 设置语言
msg.lang = 'zh-CN';
// 获取正文内容
let content = document.getElementsByClassName("post-body")[0].innerHTML;
// 修剪正文内容,去除HTML标签
let text = "";
let flag = true;
for (let i = 0; i < content.length; i++) {
// 遇到尖括号就停止朗读,再次遇到尖括号就继续朗读
if (content.charAt(i) === "<") {
flag = false;
} else if (content.charAt(i) === ">") {
flag = true;
}
// 将当前字符放到需要朗读的文本中
if (flag) {
text += content.charAt(i);
}
}
// 设置朗读内容
msg.text = text;
// 开始朗读
synth.speak(msg);
} else {
// 销毁朗读者
synth.cancel(msg);
synth = undefined;
}
}
</script>

</body>
</html>

完成

参考文献

运营狗