浏览一些博客的时候是否有看到过在内容上面有可以选择语音朗读功能,看着感觉还是蛮炫酷的。尤其是我们有针对移动端的网站阅读体验比较好,比如一些内容教程、小说类型的网站可以使用这样的功能。
这里我们一般是使用的是百度提供的TTS(Text To Speech)文本到语音功能。
以下代码加在single.php页面的任何你想插入的地方:
<?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 = "http://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 echo $qian.$r[0]; ?>" 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'); ?>/img/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'); ?>/img/bofang.png'; //暂停图片 } } </script> <span style="float: left; margin-right: 10px; cursor: pointer;">点击语音朗读 <a href="javascript:playPause();"><img src="<?php bloginfo('template_url'); ?>/img/bofang.png" width="25" height="25" id="music_btn01" border="0"></a> </span> <?php endif; ?>