You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.6 KiB
97 lines
2.6 KiB
import 'dart:async';
|
|
|
|
import 'package:flutter/services.dart';
|
|
|
|
/// 讯飞 SparkChain。事件从 [events] 来,方法调用只返回启动码。
|
|
class SparkChain {
|
|
static const _method = MethodChannel('sparkchain');
|
|
static const _events = EventChannel('sparkchain/events');
|
|
|
|
static Stream<Map<String, dynamic>>? _stream;
|
|
|
|
static Stream<Map<String, dynamic>> get events {
|
|
_stream ??= _events.receiveBroadcastStream().map((event) {
|
|
final raw = Map<Object?, Object?>.from(event as Map);
|
|
return raw.map((key, value) => MapEntry(key.toString(), value));
|
|
});
|
|
return _stream!;
|
|
}
|
|
|
|
/// 0 成功。不打印密钥。
|
|
static Future<int> init({
|
|
required String appId,
|
|
required String apiKey,
|
|
required String apiSecret,
|
|
int apiType = 1,
|
|
}) async {
|
|
final code = await _method.invokeMethod<int>('init', {
|
|
'appId': appId,
|
|
'apiKey': apiKey,
|
|
'apiSecret': apiSecret,
|
|
'apiType': apiType,
|
|
});
|
|
return code ?? -1;
|
|
}
|
|
|
|
static Future<int> translate({
|
|
required String id,
|
|
required String from,
|
|
required String to,
|
|
required String text,
|
|
}) async {
|
|
final code = await _method.invokeMethod<int>('translate', {
|
|
'id': id,
|
|
'from': from,
|
|
'to': to,
|
|
'text': text,
|
|
});
|
|
return code ?? -1;
|
|
}
|
|
|
|
static Future<int> speak({
|
|
required String id,
|
|
required String lang,
|
|
required String text,
|
|
String? voice,
|
|
}) async {
|
|
final code = await _method.invokeMethod<int>('speak', {
|
|
'id': id,
|
|
'lang': lang,
|
|
'text': text,
|
|
if (voice != null) 'voice': voice,
|
|
});
|
|
return code ?? -1;
|
|
}
|
|
|
|
/// [lang] 用短码 zh / en / ga。ga 走实时转写,其余走听写。
|
|
static Future<int> startListen({
|
|
required String id,
|
|
required String lang,
|
|
}) async {
|
|
final code = await _method.invokeMethod<int>('startListen', {
|
|
'id': id,
|
|
'lang': lang,
|
|
});
|
|
return code ?? -1;
|
|
}
|
|
|
|
static Future<int> write(Uint8List pcm) async {
|
|
final code = await _method.invokeMethod<int>('write', {'pcm': pcm});
|
|
return code ?? -1;
|
|
}
|
|
|
|
static Future<void> stopListen() async {
|
|
await _method.invokeMethod<int>('stopListen');
|
|
}
|
|
}
|
|
|
|
/// 把界面上的 BCP-47 收成插件认的短码。不认识的原样返回,让原生按失败处理。
|
|
String sparkChainShortCode(String code) {
|
|
final raw = code.trim().toLowerCase().replaceAll('_', '-');
|
|
if (raw.isEmpty) return raw;
|
|
if (raw == 'ga' || raw.startsWith('ga-')) return 'ga';
|
|
if (raw == 'zh' || raw.startsWith('zh-')) return 'zh';
|
|
if (raw == 'en' || raw.startsWith('en-')) return 'en';
|
|
final dash = raw.indexOf('-');
|
|
return dash < 0 ? raw : raw.substring(0, dash);
|
|
}
|
|
|