speechSynthesis屬於H5新增API,主要是用來做音頻合成的,最近由於項目(內網)需要對告警做音頻提示,所以用到了這個,在此簡單總結下。
先看下兼容性:
火狐谷歌瀏覽器都支持自動播放,有些是不支持的,需要引導用戶手動操作,比如點擊才生效;
直接貼代碼吧:
export const speech = (text) => { const msg = new SpeechSynthesisUtterance(); msg.text = text; //播放文案 msg.volume = '1'; // 聲音的音量,區間范圍是0到1,默認是1。 msg.rate = '1'; // 語速,數值,默認值是1,范圍是0.1到10,表示語速的倍數,例如2表示正常語速的兩倍。 msg.pitch = '0'; // 表示說話的音高,數值,范圍從0(最小)到2(最大)。默認值為1。 msg.lang = 'zh-cn'; // 使用的語言,字符串, 例如:"zh-cn"
return msg;
};
//播放 export const play = (text) => { speechSynthesis.speak(speech(text)); };
//停止 export const stop = (text) => { speechSynthesis.cancel(speech(text)); };
//直接調用即可
play('你好');
其實還可以再封裝下。
詳細API傳送門: https://developer.mozilla.org/zh-CN/docs/Web/API/SpeechSynthesisUtterance