<!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>
    <h3>点击下方按钮可以进行语音播报</h3>
    <hr />
    <button onclick="areSpeak('哈哈哈哈哈,这是声音~')">播放声音</button>  <button onclick="beQuiet()">停止播放</button>
  </body>
  <script>
    
    const areSpeak = newMsg => {
      
      virtualClick(SpeakVoice)
      speakWithDelay(newMsg)
    }
   
    const SpeakVoice = (msg = '') => {
      const speech = new SpeechSynthesisUtterance(msg)
      
      const voices = window.speechSynthesis.getVoices()
      speech.voice = voices.filter(function (voice) {
        return voice.localService == true && voice.lang == 'zh-CN'
      })[0]
      window.speechSynthesis.speak(speech)
    }
   
    const speakWithDelay = (utterance, delay = 1000) => {
      return new Promise(resolve => {
        const speech = new SpeechSynthesisUtterance(utterance)
        
        let voices = window.speechSynthesis.getVoices()
        speech.voice = voices.filter(function (voice) {
          return voice.localService == true && voice.lang == 'zh-CN'
        })[0]
        speech.onend = () => {
          setTimeout(resolve, delay)
        }
        window.speechSynthesis.speak(speech)
      })
    }
   
    const virtualClick = callback => {
      let button = document.createElement('button')
      button.textContent = '点击我'
      
      button.addEventListener('click', function () {
        console.log('按钮被点击了')
        callback && callback()
      })
      
      let event = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true
      })
      button.dispatchEvent(event)
    }
    const beQuiet = () => {
      console.log('停止')
      window.speechSynthesis.cancel()
      SpeakVoice('')
    }
    
  </script>
</html>