RIPRO美化-内页添加文本阅读(朗读)功能
文本阅读功能就是TTS(Text To Speech),即“从文本到语音”,是人机对话的一部分,让机器能够说话。
<?php
function mbStrSplit ($string, $len = 1) { //对内容进行分割
$start = 0;
$strlen = mb_strlen($string);
while ($strlen) {
$array[] = mb_substr($string,$start,$len,”utf8″);
$string = mb_substr($string, $len, $strlen,”utf8″);
$strlen = mb_strlen($string);
}
return $array;
}
function match_chinese($chars,$encoding = ‘utf8’) //过滤特殊字符串
{
$pattern = ($encoding == ‘utf8′)?’/[\x{4e00}-\x{9fa5}a-zA-Z0-9,,。 ]/u’:’/[\x80-\xFF]/’;
preg_match_all($pattern,$chars,$result);
$temp = join(”,$result[0]);
return $temp;
}
$str=$post->post_content;
$str = strip_tags($str);
$str = str_replace(“、”,”,”,$str); //保留顿号
$str = match_chinese($str);
$zishu = mb_strlen(preg_replace(‘/\s/’,”,html_entity_decode(strip_tags($str))),’UTF-8′);
$r = mbStrSplit($str, 900);
$qian = “https://tts.baidu.com/text2audio?cuid=baiduid&lan=zh&ctp=1&pdt=311&tex=”;
?>
<?php if ($zishu <= 2700): ?>
<video id=”langdu” style=”display:none”>
<source id=”source” src=”<?php%20echo%20$qian.$r[0];%20?>” type=”video/mp4″>
</video>
<script type=”text/javascript”>
function playPause() {
var music = document.getElementById(‘langdu’);
var music_btn = document.getElementById(‘music_btn01’);
if (music.paused) {
music.play();
music_btn.src = ‘<?php bloginfo(‘template_url’); ?>/images/zanting.png’; //播放图片
var aud = document.getElementById(“langdu”);
aud.onended = function() {
aud.src = “<?php echo $qian.$r[1]; ?>”
aud.play();
aud.addEventListener(“ended”, function() {
aud.src = “<?php echo $qian.$r[2]; ?>”
aud.play();
aud.addEventListener(“ended”, function() {
aud.pause();
}, false);
}, false);
};
} else {
music.pause();
music_btn.src = ‘<?php bloginfo(‘template_url’); ?>/images/bofang.png’; //暂停图片
}
}
</script>
<span style=”float: left;
margin-right: 10px;
cursor: pointer;”>
<a href=”javascript:playPause();”><img src=”<?php bloginfo(‘template_url’);
?>/images/bofang.png” width=”25″ height=”25″ id=”music_btn01″ border=”0″></a>
</span>
<?php endif; ?>
将以上代码添加到当前所用主题目录下的single.php文件中
找一个合适的位置放,根据你主题的实际情况来,ripro主题添加到parts目录下single-header.php 。
代码中用到的图片下载这两个,放在主题目录下的images目录下(可以随便放只要引用图片路径对了就可以)。至此,简单的wordpress文本朗读功能就弄好了。
图标文件可以自定义去Iconfont-阿里巴巴矢量图标库 下载上传!
我的美化完整包右边工具栏下载即可。
