VolumeTTS.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. //加一个text的预处理,将text中的数字替换成 零一二三四五六七八九十
  28. preprocessText(text) {
  29. // 将text中的数字替换成 零一二三四五六七八九十
  30. const digitMap = {
  31. '0': '零', '1': '一', '2': '二', '3': '三', '4': '四',
  32. '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'
  33. };
  34. return text.replace(/\d+/g, match => {
  35. // 逐字符替换所有数字,包括10
  36. return match.split('').map(digit => digitMap[digit] || digit).join('');
  37. });
  38. }
  39. speak(text) {
  40. text = this.preprocessText(text)
  41. // #ifdef H5
  42. // H5端使用Web Speech API
  43. if ('speechSynthesis' in window) {
  44. const utterance = new SpeechSynthesisUtterance(text)
  45. utterance.lang = this.ttsParams.lang
  46. utterance.rate = this.ttsParams.speed
  47. utterance.pitch = this.ttsParams.pitch
  48. utterance.volume = this.ttsParams.volume
  49. speechSynthesis.speak(utterance)
  50. }
  51. // #endif
  52. // #ifdef APP-PLUS
  53. let opts = this.platform == 'ios' ? {
  54. "rate": this.ttsParams.speed,
  55. "lang": "zh-CN",
  56. "volume": 1
  57. } : {
  58. "pitch": this.ttsParams.pitch,
  59. "speechRate": this.ttsParams.speed,
  60. "queueMode": 1,
  61. }
  62. this.TTSModule.speak(text, opts, (e) => {
  63. console.log(e, '读取成功')
  64. })
  65. // #endif
  66. }
  67. stop() {
  68. if (this.TTSModule) {
  69. this.TTSModule.stop()
  70. }
  71. }
  72. }
  73. export default VolumeTTS