<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>语音朗读</title> <style> body{ padding: 20px; } textarea{ 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>