[update] use aliyun andriod sdk

This commit is contained in:
2025-08-13 16:00:23 +08:00
parent a1faca7d99
commit 9202a578cd
17 changed files with 1957 additions and 181 deletions

View File

@@ -3,7 +3,12 @@ import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/services.dart';
import '../utils/common_util.dart';
class ChatSseService {
static const MethodChannel _channel = MethodChannel('com.example.ai_chat_assistant/tts');
// 缓存用户ID和会话ID
String? _cachedUserId;
String? _cachedConversationId;
@@ -11,6 +16,7 @@ class ChatSseService {
HttpClient? _currentClient;
HttpClientResponse? _currentResponse;
bool _isAborted = true;
bool isTtsStarted = false;
String? get conversationId => _cachedConversationId;
@@ -42,12 +48,21 @@ class ChatSseService {
request.add(utf8.encode(json.encode(body)));
_currentResponse = await request.close();
if (_currentResponse!.statusCode == 200) {
bool isFirst = true;
await for (final line in _currentResponse!
.transform(utf8.decoder)
.transform(const LineSplitter())) {
if (_isAborted) {
break;
}
if (isFirst) {
if (!isTtsStarted) {
if (await _channel.invokeMethod<bool>("startTts") == true) {
isTtsStarted = true;
}
}
isFirst = false;
}
if (line.startsWith('data:')) {
final jsonStr = line.substring(5).trim();
if (jsonStr == '[DONE]' || jsonStr.contains('message_end')) {
@@ -63,12 +78,16 @@ class ChatSseService {
if (jsonData['event'].toString().contains('message')) {
final textChunk =
jsonData.containsKey('answer') ? jsonData['answer'] : '';
if (_isAborted) {
break;
}
_channel.invokeMethod("sendTts", {"text": CommonUtil.cleanText(textChunk, true)});
responseText += textChunk;
tempText += textChunk;
int endIndex = _getCompleteTextEndIndex(tempText);
final completeText = tempText.substring(0, endIndex).trim();
tempText = tempText.substring(endIndex).trim();
onStreamResponse(messageId, responseText, completeText, false);
// tempText += textChunk;
// int endIndex = _getCompleteTextEndIndex(tempText);
// final completeText = tempText.substring(0, endIndex).trim();
// tempText = tempText.substring(endIndex).trim();
onStreamResponse(messageId, responseText, "completeText", false);
}
} catch (e) {
print('解析 SSE 数据出错: $e, 原始数据: $jsonStr');
@@ -81,12 +100,15 @@ class ChatSseService {
} catch (e) {
// todo
} finally {
isTtsStarted = false;
resetRequest();
}
}
Future<void> abort() async {
_isAborted = true;
_channel.invokeMethod("stopTts");
isTtsStarted = false;
resetRequest();
}