# All files / modules/tts aliyun-realtime.provider.ts

0% Statements 0/118
0% Branches 0/1
0% Functions 0/1
0% Lines 0/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160

     import WebSocket from 'ws';
    import fs from 'fs';
    import path from 'path';
    import { config } from '../../config';
    import { VoiceParams } from '../../types';

    // 阿里云百炼 Qwen-TTS WebSocket 实时语音合成
    // 文档: https://help.aliyun.com/zh/model-studio/qwen-tts-realtime
    // 支持流式输入，适合长文本

    export class AliyunRealtimeTtsProvider {
      private apiKey: string;
      private model: string;
      private voice: string;
      private baseUrl = 'wss://dashscope.aliyuncs.com/api-ws/v1/realtime';

      constructor() {
        // 从 models.json 统一获取百炼配置（已消除 dashscope 冗余配置源）
        const vendorConfig = (config.models as any).vendors?.bailian;
        this.apiKey = vendorConfig?.apiKey || '';
        this.model = this.model || 'qwen3-tts-instruct-flash-realtime';
        this.voice = (config.models as any).tts?.defaultVoice || 'Cherry';
      }

      // 语音合成（WebSocket 流式）
      async synthesize(
        text: string,
        voiceId: string,
        params: VoiceParams,
        outputPath: string
      ): Promise<string> {
        return new Promise((resolve, reject) => {
          const voice = voiceId || this.voice;
          const audioChunks: Buffer[] = [];
          let sessionId: string;

          console.log('🔊 [Qwen Realtime TTS] 建立 WebSocket 连接...');

          const ws = new WebSocket(this.baseUrl, {
            headers: {
              'Authorization': `Bearer ${this.apiKey}`,
              'X-DashScope-App': 'audio-tts',
            },
          });

          ws.on('open', () => {
            console.log('✅ [Qwen Realtime TTS] 连接已建立');
          });

          ws.on('message', (data) => {
            try {
              const message = JSON.parse(data.toString());

              switch (message.event) {
                case 'session.configed':
                  // 配置成功，发送文本
                  sessionId = message.session_id;
                  console.log('📝 [Qwen Realtime TTS] Session ID:', sessionId);

                  // 构建指令
                  const instructions: string[] = [];
                  if (params.speed !== 1) {
                    const speedDesc = params.speed > 1 ? '语速较快' : '语速较慢';
                    instructions.push(speedDesc);
                  }
                  if (params.pitch !== 0) {
                    const pitchDesc = params.pitch > 0 ? '音调较高' : '音调较低';
                    instructions.push(pitchDesc);
                  }

                  // 使用 server_commit 模式：直接发送完整文本，服务端自动处理分段
                  const textMessage = {
                    event: 'input_text_buffer.append',
                    context: {
                      text: text,
                    },
                  };
                  ws.send(JSON.stringify(textMessage));
                  console.log('📤 [Qwen Realtime TTS] 文本已发送，长度:', text.length);

                  // 发送 commit 触发合成
                  const commitMessage = {
                    event: 'input_text_buffer.commit',
                  };
                  ws.send(JSON.stringify(commitMessage));
                  console.log('📤 [Qwen Realtime TTS] 触发语音合成...');
                  break;

                case 'audio.stream':
                  // 接收音频数据
                  if (message.data) {
                    const audioBuffer = Buffer.from(message.data, 'base64');
                    audioChunks.push(audioBuffer);
                  }
                  break;

                case 'audio.finish':
                  // 合成完成
                  console.log('✅ [Qwen Realtime TTS] 合成完成');

                  // 保存文件
                  if (audioChunks.length > 0) {
                    const dir = path.dirname(outputPath);
                    if (!fs.existsSync(dir)) {
                      fs.mkdirSync(dir, { recursive: true });
                    }

                    const finalPath = outputPath.endsWith('.mp3') ? outputPath : outputPath.replace(/\.[^.]+$/, '.mp3');
                    const finalBuffer = Buffer.concat(audioChunks);
                    fs.writeFileSync(finalPath, finalBuffer);
                    console.log(`✅ [Qwen Realtime TTS] 文件已保存: ${finalPath}, 大小: ${finalBuffer.length} bytes`);
                    ws.close();
                    resolve(finalPath);
                  } else {
                    ws.close();
                    reject(new Error('Qwen Realtime TTS 未返回音频数据'));
                  }
                  break;

                case 'task.finished':
                  // 任务完成
                  ws.close();
                  resolve(outputPath);
                  break;

                case 'error':
                  console.error('❌ [Qwen Realtime TTS] 错误:', message.message);
                  ws.close();
                  reject(new Error(`Qwen Realtime TTS 错误: ${message.message}`));
                  break;

                default:
                  // 忽略其他消息
                  break;
              }
            } catch (err) {
              console.error('❌ [Qwen Realtime TTS] 解析消息失败:', err);
            }
          });

          ws.on('error', (err) => {
            console.error('❌ [Qwen Realtime TTS] WebSocket 错误:', err.message);
            reject(err);
          });

          ws.on('close', () => {
            console.log('🔌 [Qwen Realtime TTS] 连接已关闭');
          });

          // 超时处理
          setTimeout(() => {
            if (ws.readyState === WebSocket.OPEN) {
              ws.close();
              reject(new Error('Qwen Realtime TTS 请求超时'));
            }
          }, 120000); // 2分钟超时
        });
      }
    }