VolumeTTS.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. class VolumeTTS {
  2. ttsParams = {
  3. lang: 'zh-CN',
  4. speed: 1, // 将 0-10 转换为 0-1
  5. pitch: 1, // 将 0-10 转换为 0-1
  6. volume: 1,
  7. };
  8. TTSModule;
  9. platform = uni.getSystemInfoSync().platform
  10. constructor(opts) {
  11. if (opts) this.ttsParams = opts;
  12. // #ifdef APP-PLUS
  13. this.init()
  14. // #endif
  15. }
  16. init() {
  17. this.TTSModule = uni.requireNativePlugin('nrb-tts-plugin')
  18. this.TTSModule && this.TTSModule.init({
  19. "lang": "ZH",
  20. "country": "CN"
  21. }, res => {
  22. if (res.success == 0) {
  23. console.log('TTS初始化成功')
  24. }
  25. })
  26. }
  27. speak(text) {
  28. // #ifdef H5
  29. // H5端使用Web Speech API
  30. if ('speechSynthesis' in window) {
  31. const utterance = new SpeechSynthesisUtterance(text)
  32. utterance.lang = this.ttsParams.lang
  33. utterance.rate = this.ttsParams.speed
  34. utterance.pitch = this.ttsParams.pitch
  35. utterance.volume = this.ttsParams.volume
  36. speechSynthesis.speak(utterance)
  37. }
  38. // #endif
  39. console.log(this.platform, 'dsad');
  40. // #ifdef APP-PLUS
  41. let opts = this.platform == 'ios' ? {
  42. "rate": this.ttsParams.speed,
  43. "lang": "zh-CN",
  44. "volume": 1
  45. } : {
  46. "pitch": this.ttsParams.pitch,
  47. "speechRate": this.ttsParams.speed,
  48. "queueMode": 1,
  49. }
  50. console.log(this.TTSModule,'this.TTSModule')
  51. this.TTSModule.speak(text, opts, (e) => {
  52. console.log(e, '读取成功')
  53. })
  54. // #endif
  55. }
  56. stop() {
  57. if (this.TTSModule) {
  58. this.TTSModule.stop()
  59. }
  60. }
  61. }
  62. export default VolumeTTS