VolumeTTS.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. let audioConfig = uni.getStorageSync("audioConfig");
  12. if (opts) {
  13. this.ttsParams = opts;
  14. } else if (audioConfig) {
  15. this.ttsParams = {
  16. lang: "zh-CN",
  17. speed: audioConfig.audioSpeed / 10,
  18. pitch: audioConfig.audioVolume,
  19. volume: 1,
  20. };
  21. }
  22. // #ifdef APP-PLUS
  23. this.init();
  24. // #endif
  25. }
  26. init() {
  27. this.TTSModule = uni.requireNativePlugin("nrb-tts-plugin");
  28. this.TTSModule &&
  29. this.TTSModule.init(
  30. {
  31. lang: "zh",
  32. country: "CN",
  33. },
  34. (res) => {
  35. if (res.success == 0) {
  36. console.log("TTS初始化成功");
  37. }
  38. }
  39. );
  40. }
  41. //加一个text的预处理,将text中的数字替换成 零一二三四五六七八九十
  42. preprocessText(text) {
  43. // 将text中的数字替换成 零一二三四五六七八九十
  44. const digitMap = {
  45. 0: "零",
  46. 1: "一",
  47. 2: "二",
  48. 3: "三",
  49. 4: "四",
  50. 5: "五",
  51. 6: "六",
  52. 7: "七",
  53. 8: "八",
  54. 9: "九",
  55. };
  56. return text.replace(/\d+/g, (match) => {
  57. // 逐字符替换所有数字,包括10
  58. return match
  59. .split("")
  60. .map((digit) => digitMap[digit] || digit)
  61. .join("");
  62. });
  63. }
  64. speak(text) {
  65. text = this.preprocessText(text);
  66. // #ifdef H5
  67. // H5端使用Web Speech API
  68. if ("speechSynthesis" in window) {
  69. const utterance = new SpeechSynthesisUtterance(text);
  70. utterance.lang = this.ttsParams.lang;
  71. utterance.rate = this.ttsParams.speed;
  72. utterance.pitch = this.ttsParams.pitch;
  73. utterance.volume = this.ttsParams.volume;
  74. speechSynthesis.speak(utterance);
  75. }
  76. // #endif
  77. // #ifdef APP-PLUS
  78. let opts =
  79. this.platform == "ios"
  80. ? {
  81. rate: this.ttsParams.speed,
  82. lang: "zh-CN",
  83. volume: 1,
  84. }
  85. : {
  86. pitch: this.ttsParams.pitch,
  87. speechRate: this.ttsParams.speed,
  88. queueMode: 1,
  89. };
  90. this.TTSModule.speak(text, opts, (e) => {
  91. console.log(e, "读取成功");
  92. });
  93. // #endif
  94. }
  95. stop() {
  96. if (this.TTSModule) {
  97. this.TTSModule.stop();
  98. }
  99. }
  100. }
  101. export default VolumeTTS;