ttsManager.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // ttsManager.js
  2. import {
  3. getBaiduTTSUrl,
  4. getBaiduTTSAccessToken
  5. } from '@/common/js/tts.js'
  6. class TTSManager {
  7. constructor() {
  8. this.isSpeaking = false;
  9. this.messageQueue = [];
  10. this.audioContext = null;
  11. this.initAudio();
  12. }
  13. initAudio() {
  14. this.audioContext = uni.createInnerAudioContext();
  15. this.audioContext.onEnded(() => {
  16. this.isSpeaking = false;
  17. this.playNext(); // 播放下一句
  18. });
  19. this.audioContext.onError((error) => {
  20. console.error('音频播放错误:', error);
  21. this.isSpeaking = false;
  22. this.playNext();
  23. });
  24. }
  25. async speak(text) {
  26. // 如果正在播放,将新消息加入队列
  27. if (this.isSpeaking) {
  28. this.messageQueue.push(text);
  29. return;
  30. }
  31. this.isSpeaking = true;
  32. try {
  33. const token = await getBaiduTTSAccessToken();
  34. console.log(token,'11111111111111111');
  35. console.log(text,'22222222222222222');
  36. const audioUrl = getBaiduTTSUrl(text, token);
  37. this.audioContext.src = audioUrl;
  38. console.log(text,'3333333333333');
  39. this.audioContext.play();
  40. } catch (error) {
  41. console.error('TTS合成失败:', error);
  42. this.isSpeaking = false;
  43. }
  44. }
  45. playNext() {
  46. if (this.messageQueue.length > 0) {
  47. const nextText = this.messageQueue.shift();
  48. this.speak(nextText);
  49. }
  50. }
  51. destroy() {
  52. if (this.audioContext) {
  53. this.audioContext.destroy();
  54. }
  55. }
  56. }
  57. export default new TTSManager();