<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>語音朗讀</title>
<style>
body{
padding: 20px;
}
textarea{
width: 100%;
height: 260px;
}
</style>
</head>
<body>
<textarea name="" cols="30" rows="10" id="sppekContent" placeholder="輸入一些內容試試..."></textarea>
<a href="javascript:;" id="du">朗讀</a>
<a href="javascript:;" id="zanting">暫停</a>
<a href="javascript:;" id="chongxing">重新開始</a>
<a href="javascript:;" id="stop">停止</a>
<script>
window.onload=function () {
/**
* @returns {{start: start, pause: pause, resume: resume, stop: stop}}
*/
function speek(){
let speechInstance = new SpeechSynthesisUtterance();
// console.log(speechInstance);
// console.log(speechSynthesis.getVoices());
return {
/**
* @param opitions {container:'',Lang:''}
*/
start:function (opitions) {
let container=opitions.container;
let lang=opitions.Lang===undefined||""?"zh-CN":opitions.Lang;
let content=document.querySelector(container).value;
if(content!='') {
speechInstance.text = content;
speechInstance.lang = lang;
speechSynthesis.speak(speechInstance);
}else{
console.log("請輸入內容");
}
},
pause:function () {
speechSynthesis.pause();//暫停
},
resume:function(){
speechSynthesis.resume();//重新開始
},
stop:function () {
speechSynthesis.cancel();//結束
}
}
}
document.querySelector("#du").onclick=function () {
speek().start({container:"#sppekContent",Lang:''});
};
document.querySelector("#zanting").onclick=function () {
speek().pause();
};
document.querySelector("#chongxing").onclick=function () {
speek().resume();
};
document.querySelector("#stop").onclick=function () {
speek().stop();
}
}
</script>
</body>
</html>