由于网页设计大赛的事,想要搞点高级货,但是这周五就要交稿了,所以折腾一点没那么难的却很酷炫的功能。
你可以预先设定待会要被播放的文本。
fetch('https://v1.hitokoto.cn') .then(response => response.json()) .then(data => { const hitokoto = document.getElementById('textarea-1') hitokoto.href = 'https://hitokoto.cn/?uuid=' + data.uuid hitokoto.innerText = data.hitokoto }) .catch(console.error)
天使坠落之时…
这里一个除了IE以外的主流浏览器可以使用的功能
var sound = window.speechSynthesis; // 定义局部变量
var read_text = new SpeechSynthesisUtterance(text); // 实例化
sound.speak(read_text); // 朗读
其中将text改成你所需要朗读的文本,或者取变量里面的值。
var sound = window.speechSynthesis;
var read_text = new SpeechSynthesisUtterance($("#textarea").text());
sound.speak(read_text);
function read_1() { var sound = window.speechSynthesis; var read_text = new SpeechSynthesisUtterance($('#textarea-1').text()); sound.speak(read_text); }
阅读
但是这样你会发现一个问题:播放时浏览器并不会提示,甚至可能无法方便的暂停。 但是也不是没有好处的,因为这不需要白嫖API接口,就是兼容性有些差。
所以我们可以白嫖百度TTS接口啊(滑稽)
audio = document.createElement('audio'); // 声明audio全局变量并创建元素
source = document.createElement('source'); // 声明source全局变量并创建元素
source.type = "audio/mpeg"; // source类型
source.src = 'https://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=8&text=' + $('#textarea').text(); // 拼接URL并读取要朗读的内容,设定src地址
source.autoplay = "autoplay"; // 自动播放
source.controls = "controls"; // 显示控件(其实没必要)
audio.appendChild(source); // 作为source的父元素
audio.play(); // 播放
audio = document.createElement('audio');
source = document.createElement('source');
source.type = "audio/mpeg";
source.src = 'https://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=8&text=' + $('#textarea').text();
source.autoplay = "autoplay";
audio.appendChild(source);
audio.play();
function read_2() { audio = document.createElement('audio'); source = document.createElement('source'); source.type = "audio/mpeg"; source.src = 'https://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=8&text=' + $('#textarea-1').text(); source.autoplay = "autoplay"; audio.appendChild(source); audio.play(); }阅读
优点:使用audio标签,可控音频播放。 缺点:需要联网。