場景
在網頁端實現將指定的文字進行語音合成並進行播報。
使用HTML5的Speech Synthesis API就能實現簡單的語音合成效果。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
新建一個Html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name= "viewport"content="width=device-width, initial-scale=1.0"> <title>公眾號:霸道的程序猿</title> </head> <body> <h1>公眾號:霸道的程序猿</h1> <input id="btn1" type="button" value ="點我" onclick="test();"/> </body> </html> <script> function test() { const sos = `公眾號:霸道的程序猿`; const synth = window.speechSynthesis; let msg = new SpeechSynthesisUtterance(sos); synth.speak(msg) } </script>
然后在瀏覽器中打開


然后點擊按鈕,就會觸發test方法的執行
const sos = `公眾號:霸道的程序猿`;
const synth = window.speechSynthesis;
let msg = new SpeechSynthesisUtterance(sos);
synth.speak(msg)
然后實現語音合成的主要是如上代碼。
這里推薦使用Chrome瀏覽器,因為HTML5的支持度不同
瀏覽器兼容性
| 電腦端 | 移動端 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | |
| 基本支持 | 支持:33 | 支持 | 支持:49 | 支持 | ? | 支持:7 | ? | 支持 | 支持 | 支持 | 支持 | 支持:7.1 |
