| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- // ttsManager.js
- import {
- getBaiduTTSUrl,
- getBaiduTTSAccessToken
- } from '@/common/js/tts.js'
- class TTSManager {
- constructor() {
- this.isSpeaking = false;
- this.messageQueue = [];
- this.audioContext = null;
- this.initAudio();
- }
- initAudio() {
- this.audioContext = uni.createInnerAudioContext();
- this.audioContext.onEnded(() => {
- this.isSpeaking = false;
- this.playNext(); // 播放下一句
- });
- this.audioContext.onError((error) => {
- console.error('音频播放错误:', error);
- this.isSpeaking = false;
- this.playNext();
- });
- }
- async speak(text) {
- // 如果正在播放,将新消息加入队列
- if (this.isSpeaking) {
- this.messageQueue.push(text);
- return;
- }
- this.isSpeaking = true;
- try {
- const token = await getBaiduTTSAccessToken();
- const audioUrl = getBaiduTTSUrl(text, token);
- this.audioContext.src = audioUrl;
- this.audioContext.play();
- } catch (error) {
- console.error('TTS合成失败:', error);
- this.isSpeaking = false;
- }
- }
- playNext() {
- if (this.messageQueue.length > 0) {
- const nextText = this.messageQueue.shift();
- this.speak(nextText);
- }
- }
- destroy() {
- if (this.audioContext) {
- this.audioContext.destroy();
- }
- }
- }
- export default new TTSManager();
|