voiceBroadcast.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * @description 文字转语音方法
  3. * @public
  4. * @param { text, rate, lang, volume, pitch } object
  5. * @param text 要合成的文字内容,字符串
  6. * @param rate 读取文字的语速 0.1~10 正常1
  7. * @param lang 读取文字时的语言
  8. * @param volume 读取时声音的音量 0~1 正常1
  9. * @param pitch 读取时声音的音高 0~2 正常1
  10. * @returns SpeechSynthesisUtterance
  11. */
  12. export default function speak ({ text, speechRate, lang, volume, pitch }, endEvent, startEvent) {
  13. if (!window.SpeechSynthesisUtterance) {
  14. console.warn('当前浏览器不支持文字转语音服务')
  15. return
  16. }
  17. if (!text) {
  18. return
  19. }
  20. const speechUtterance = new SpeechSynthesisUtterance()
  21. speechUtterance.text = text
  22. speechUtterance.rate = speechRate || 1
  23. speechUtterance.lang = lang || 'zh-CN'
  24. speechUtterance.volume = volume || 1
  25. speechUtterance.pitch = pitch || 1
  26. speechUtterance.onend = function () {
  27. endEvent && endEvent()
  28. }
  29. speechUtterance.onstart = function () {
  30. startEvent && startEvent()
  31. }
  32. speechSynthesis.speak(speechUtterance)
  33. }