feat: 增加在线语音 SDK 和音色管理后台,完善引擎适配

This commit is contained in:
tongtong committed 2026-11-23 19:02:44 +08:00
1 parent 1856de97bc
commit a532ba4e0f
71 files changed
+3189 -472

No files matched your search

+2 -1
View File
@@ -23,4 +23,5 @@ android {
abortOnError false
checkReleaseBuilds = false
}
}
}
dependencies { implementation 'com.ttstd:tts-speaker-sdk:1.0.0' }
+3 -4
View File
@@ -1,13 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<queries>
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
<intent><action android:name="android.intent.action.TTS_SERVICE" /></intent>
<package android:name="com.ttstd.tts.engine" />
</queries>
<application
android:allowBackup="false"
android:label="@string/app_name"
@@ -0,0 +1,84 @@
package com.ttstd.tts.testclient;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.*;
import com.ttstd.tts.sdk.OnlineTtsClient;
import com.ttstd.tts.sdk.SpeechRequest;
import java.util.*;
/** Optional system-engine test path; never initialized by the direct SDK mode. */
final class EngineTtsTester implements AutoCloseable {
static final String PACKAGE="com.ttstd.tts.engine";
private final Context context;
private final Handler main=new Handler(Looper.getMainLooper());
private TextToSpeech tts;
private boolean ready, closed;
private Runnable pending;
private OnlineTtsClient.Listener pendingListener;
private final Map<String,OnlineTtsClient.Listener> listeners=new HashMap<>();
EngineTtsTester(Context context) { this.context=context.getApplicationContext(); }
void speak(SpeechRequest request,boolean network,OnlineTtsClient.Listener callback) {
stop();
if(closed) return;
if(ready) { play(request,network,callback); return; }
pending=() -> play(request,network,callback);
pendingListener=callback;
if(tts!=null) return;
try { context.getPackageManager().getPackageInfo(PACKAGE,0); }
catch(Exception e) { failPending("未安装 TTStd 系统引擎"); return; }
tts=new TextToSpeech(context,status -> {
if(closed) return;
if(status!=TextToSpeech.SUCCESS) {
TextToSpeech failed=tts; tts=null;
if(failed!=null) failed.shutdown();
failPending("系统引擎初始化失败"); return;
}
ready=true;
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
public void onStart(String id) { main.post(() -> { OnlineTtsClient.Listener l=listeners.get(id); if(l!=null) l.onStart(); }); }
public void onDone(String id) { main.post(() -> { OnlineTtsClient.Listener l=listeners.remove(id); if(l!=null) l.onCompleted(); }); }
public void onError(String id) { onError(id,TextToSpeech.ERROR_SYNTHESIS); }
public void onError(String id,int error) { main.post(() -> { OnlineTtsClient.Listener l=listeners.remove(id); if(l!=null) l.onError(0,"系统引擎错误 "+error); }); }
public void onStop(String id,boolean interrupted) { main.post(() -> { OnlineTtsClient.Listener l=listeners.remove(id); if(l!=null) l.onCancelled(); }); }
});
Runnable next=pending; pending=null; pendingListener=null;
if(next!=null) next.run();
},PACKAGE);
}
private void play(SpeechRequest request,boolean network,OnlineTtsClient.Listener listener) {
Set<Voice> voices=tts.getVoices();
Voice selected=null;
if(voices!=null) for(Voice voice:voices) {
if(voice.isNetworkConnectionRequired()==network && voice.getLocale().getLanguage().equals("zh")) {
selected=voice; break;
}
}
if(selected==null || tts.setVoice(selected)!=TextToSpeech.SUCCESS) {
listener.onError(0,"所选引擎音色不可用;离线模式需要安装语音包"); return;
}
android.util.Log.i("TtsTestClient","引擎测试音色 "+selected.getName()+" network="+network);
tts.setSpeechRate(request.speed); tts.setPitch(request.pitch);
String id=UUID.randomUUID().toString(); listeners.put(id,listener);
if(tts.speak(request.text,TextToSpeech.QUEUE_FLUSH,new Bundle(),id)!=TextToSpeech.SUCCESS) {
listeners.remove(id); listener.onError(0,"系统引擎拒绝朗读请求");
}
}
private void failPending(String message) {
OnlineTtsClient.Listener listener=pendingListener;
pending=null; pendingListener=null;
if(listener!=null) listener.onError(0,message);
}
void stop() {
pending=null;
OnlineTtsClient.Listener waiting=pendingListener; pendingListener=null;
if(tts!=null) tts.stop();
List<OnlineTtsClient.Listener> cancelled=new ArrayList<>(listeners.values()); listeners.clear();
if(waiting!=null) waiting.onCancelled();
for(OnlineTtsClient.Listener listener:cancelled) listener.onCancelled();
}
@Override public void close() { closed=true; stop(); if(tts!=null) { tts.shutdown(); tts=null; } }
}
@@ -1,221 +1,146 @@
package com.ttstd.tts.testclient;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.speech.tts.Voice;
import android.text.method.ScrollingMovementMethod;
import android.text.InputType;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.widget.*;
import com.ttstd.tts.sdk.OnlineTtsClient;
import com.ttstd.tts.sdk.SpeechRequest;
import java.util.Locale;
import java.util.Set;
/** Direct Maven SDK sample: no binding to an installed TextToSpeech engine. */
public class MainActivity extends Activity {
private static final String TAG = "TtsTestClient";
private static final String ENGINE = "com.ttstd.tts.engine";
private static final String[] SWEEP_TEXTS = {"一", "二", "三", "四", "五", "六"};
private static final String TAG="TtsTestClient";
private OnlineTtsClient client;
private EngineTtsTester engine;
private Spinner mode;
private int selectedMode;
private SharedPreferences prefs;
private EditText text;
private SeekBar rate,pitch;
private TextView log;
private boolean batch;
private int index;
private int sequence;
private final float[] rates={0.5f,1f,1.5f,2f,1f,1f};
private final float[] pitches={1f,1f,1f,1f,0.5f,2f};
private TextView logView;
private TextView rateLabel;
private TextView pitchLabel;
private EditText textInput;
private SeekBar rateBar;
private SeekBar pitchBar;
private TextToSpeech tts;
private boolean ready;
private int utteranceSeq;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_main);
logView = findViewById(R.id.log_view);
logView.setMovementMethod(new ScrollingMovementMethod());
textInput = findViewById(R.id.text_input);
rateBar = findViewById(R.id.rate_bar);
pitchBar = findViewById(R.id.pitch_bar);
rateLabel = findViewById(R.id.rate_label);
pitchLabel = findViewById(R.id.pitch_label);
SeekBar.OnSeekBarChangeListener labels = new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
updateLabels();
}
public void onStartTrackingTouch(SeekBar bar) {
}
public void onStopTrackingTouch(SeekBar bar) {
text=findViewById(R.id.text_input);
rate=findViewById(R.id.rate_bar);
pitch=findViewById(R.id.pitch_bar);
log=findViewById(R.id.log_view);
log.setMovementMethod(new android.text.method.ScrollingMovementMethod());
engine=new EngineTtsTester(this);
mode=findViewById(R.id.synthesis_mode);
mode.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item,
new String[]{"SDK 直接在线(无需引擎)","系统引擎离线","系统引擎在线"}));
selectedMode=getIntent().getIntExtra("mode",0);
mode.setSelection(selectedMode);
mode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,android.view.View view,int position,long id) {
if(position!=selectedMode) { selectedMode=position; stop(); }
}
public void onNothingSelected(AdapterView<?> parent) {}
});
findViewById(R.id.btn_engine_config).setOnClickListener(v -> {
try { startActivity(new android.content.Intent().setComponent(new android.content.ComponentName(
EngineTtsTester.PACKAGE,EngineTtsTester.PACKAGE+".SettingsActivity"))); }
catch(Exception e) { append("未安装系统引擎,请先安装引擎 APK"); }
});
prefs=getSharedPreferences("tts_sdk_test",MODE_PRIVATE);
SeekBar.OnSeekBarChangeListener labels=new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar b,int p,boolean u) { updateLabels(); }
public void onStartTrackingTouch(SeekBar b) {}
public void onStopTrackingTouch(SeekBar b) {}
};
rateBar.setOnSeekBarChangeListener(labels);
pitchBar.setOnSeekBarChangeListener(labels);
updateLabels();
findViewById(R.id.btn_speak).setOnClickListener(v -> speak());
rate.setOnSeekBarChangeListener(labels); pitch.setOnSeekBarChangeListener(labels); updateLabels();
findViewById(R.id.btn_speak).setOnClickListener(v -> {
batch=false; speak(text.getText().toString(),value(rate),value(pitch),false);
});
findViewById(R.id.btn_stop).setOnClickListener(v -> stop());
findViewById(R.id.btn_sweep).setOnClickListener(v -> sweep());
initTts();
}
private void initTts() {
appendLog("连接引擎 " + ENGINE);
tts = new TextToSpeech(this, status -> {
appendLog("onInit status=" + status);
if (status != TextToSpeech.SUCCESS) {
appendLog("引擎初始化失败");
return;
}
ready = true;
logEngines();
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
appendLog("开始合成 " + utteranceId);
}
@Override
public void onDone(String utteranceId) {
appendLog("播放完成 " + utteranceId);
}
@Override
public void onError(String utteranceId) {
appendLog("合成/播放失败 " + utteranceId);
}
});
appendLog("setLanguage zh-CN -> " + tts.setLanguage(Locale.SIMPLIFIED_CHINESE));
listVoices();
if (getIntent().getBooleanExtra("autosweep", false)) sweep();
else if (getIntent().getBooleanExtra("autospeak", false)) {
long delay = getIntent().getLongExtra("speak_delay_ms", 0);
if (delay > 0) logView.postDelayed(this::speak, delay);
else speak();
}
}, ENGINE);
}
private void logEngines() {
List<TextToSpeech.EngineInfo> engines = tts.getEngines();
appendLog("系统引擎数量 " + engines.size());
for (TextToSpeech.EngineInfo engine : engines) {
appendLog("引擎 " + engine.name + " | " + engine.label);
findViewById(R.id.btn_sweep).setOnClickListener(v -> { stop(); batch=true; index=0; next(); });
findViewById(R.id.btn_online_config).setOnClickListener(v -> configure());
findViewById(R.id.btn_online_error).setOnClickListener(v -> {
char[] chars=new char[301]; java.util.Arrays.fill(chars,'一');
speak(new String(chars),1,1,false);
});
createClient();
append("已加载 Maven SDK com.ttstd:tts-speaker-sdk:1.0.0;无需引擎 APK");
if(getIntent().getBooleanExtra("autoerror",false)) findViewById(R.id.btn_online_error).performClick();
else if(getIntent().getBooleanExtra("autosweep",false)) { batch=true; index=0; next(); }
else if(getIntent().getBooleanExtra("autospeak",false)) {
speak(text.getText().toString(),value(rate),value(pitch),false);
if(getIntent().getBooleanExtra("autocancel",false)) log.postDelayed(this::stop,300);
}
List<ResolveInfo> services = getPackageManager().queryIntentServices(
new Intent("android.intent.action.TTS_SERVICE"), 0);
appendLog("PM TTS 服务数量(flags=0) " + (services == null ? -1 : services.size()));
if (services != null) {
for (ResolveInfo info : services) {
if (info.serviceInfo != null) {
appendLog("PM 服务 " + info.serviceInfo.packageName + "/" + info.serviceInfo.name);
}
}
}
Intent explicit = new Intent("android.intent.action.TTS_SERVICE").setPackage(ENGINE);
List<ResolveInfo> explicitServices = getPackageManager().queryIntentServices(explicit, 0);
appendLog("显式包查询数量 " + (explicitServices == null ? -1 : explicitServices.size()));
}
private boolean createClient() {
try {
getPackageManager().getPackageInfo(ENGINE, 0);
appendLog("getPackageInfo(" + ENGINE + ") 可见");
} catch (Exception e) {
appendLog("getPackageInfo(" + ENGINE + ") 不可见: " + e.getClass().getSimpleName());
}
client=new OnlineTtsClient(this,prefs.getString("url",OnlineTtsClient.DEFAULT_ENDPOINT),
() -> prefs.getString("token",""));
return true;
} catch(IllegalArgumentException e) { append("服务地址无效,请重新配置 HTTPS 地址"); return false; }
}
private void listVoices() {
Set<Voice> voices = tts.getVoices();
if (voices == null) {
appendLog("getVoices() = null");
return;
}
appendLog("语音数量 " + voices.size());
for (Voice voice : voices) {
appendLog("语音 " + voice.getName() + " | " + voice.getLocale().toLanguageTag()
+ " | q=" + voice.getQuality());
}
private void speak(String content,float speed,float tone,boolean sweep) {
if(client==null && mode.getSelectedItemPosition()==0) { append("请先配置服务地址"); return; }
String id=(sweep?"sweep-":"utt-")+(++sequence);
try {
SpeechRequest request=new SpeechRequest(content,speed,tone);
append(String.format(Locale.ROOT,"模式=%s %s speed=%.2f pitch=%.2f",mode.getSelectedItem(),id,speed,tone));
OnlineTtsClient.Listener listener=new OnlineTtsClient.Listener() {
public void onStart() { append("播放开始 "+id); }
public void onCompleted() { append("播放完成 "+id); if(sweep && batch) next(); }
public void onError(int status,String message) { batch=false; append("在线合成失败 "+id+" HTTP="+status+" "+message); }
public void onCancelled() { append("已停止 "+id); }
};
if(mode.getSelectedItemPosition()==0) client.speak(request,listener);
else engine.speak(request,mode.getSelectedItemPosition()==2,listener);
} catch(IllegalArgumentException e) { append("参数校验失败:"+e.getMessage()); }
}
private void speak() {
if (!ready) {
appendLog("引擎未就绪");
return;
}
String text = textInput.getText().toString().trim();
if (text.isEmpty()) {
appendLog("文本为空");
return;
}
float rate = rate();
float pitch = pitch();
tts.setSpeechRate(rate);
tts.setPitch(pitch);
String id = "utt-" + (++utteranceSeq);
int result = tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, id);
appendLog(String.format(Locale.ROOT, "speak %s speed=%.2f pitch=%.2f -> %d", id, rate, pitch, result));
private void next() {
if(index>=rates.length) { batch=false; append("六组 SDK 参数用例全部完成"); return; }
int current=index++;
speak("您好,现在测试在线语音合成。",rates[current],pitches[current],true);
}
private void sweep() {
if (!ready) {
appendLog("引擎未就绪");
return;
}
float[] rates = {0.5f, 1.0f, 1.5f, 2.0f, 1.0f, 1.0f};
float[] pitches = {1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 2.0f};
for (int i = 0; i < rates.length; i++) {
tts.setSpeechRate(rates[i]);
tts.setPitch(pitches[i]);
String id = "sweep-" + (++utteranceSeq);
tts.speak(SWEEP_TEXTS[i], TextToSpeech.QUEUE_ADD, null, id);
appendLog(String.format(Locale.ROOT, "%s speed=%.2f pitch=%.2f", id, rates[i], pitches[i]));
}
}
private void stop() {
if (tts != null) {
tts.stop();
appendLog("stop()");
}
}
private float rate() {
return (50 + rateBar.getProgress()) / 100f;
}
private float pitch() {
return (50 + pitchBar.getProgress()) / 100f;
}
private void stop() { batch=false; if(client!=null) client.stop(); if(engine!=null) engine.stop(); append("stop()"); }
private float value(SeekBar bar) { return (50+bar.getProgress())/100f; }
private void updateLabels() {
rateLabel.setText(getString(R.string.rate_label, rate()));
pitchLabel.setText(getString(R.string.pitch_label, pitch()));
((TextView)findViewById(R.id.rate_label)).setText(getString(R.string.rate_label,value(rate)));
((TextView)findViewById(R.id.pitch_label)).setText(getString(R.string.pitch_label,value(pitch)));
}
private void appendLog(String message) {
Log.i(TAG, message);
String line = new SimpleDateFormat("HH:mm:ss", Locale.ROOT).format(new Date()) + " " + message;
logView.append(line + "\n");
private void configure() {
LinearLayout fields=new LinearLayout(this); fields.setOrientation(LinearLayout.VERTICAL);
int padding=(int)(16*getResources().getDisplayMetrics().density); fields.setPadding(padding,padding,padding,padding);
EditText url=new EditText(this); url.setHint("HTTPS 合成接口");
url.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_URI);
url.setText(prefs.getString("url",OnlineTtsClient.DEFAULT_ENDPOINT)); fields.addView(url);
EditText token=new EditText(this); token.setHint("访问令牌"); token.setSaveEnabled(false);
token.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
token.setText(prefs.getString("token","")); fields.addView(token);
new AlertDialog.Builder(this).setTitle("SDK 在线合成配置").setView(fields)
.setPositiveButton("保存",(d,w) -> {
String endpoint=url.getText().toString().trim();
try { OnlineTtsClient check=new OnlineTtsClient(this,endpoint,() -> ""); check.close(); }
catch(IllegalArgumentException e) { append("HTTPS 地址无效,未保存"); return; }
batch=false;
if(client!=null) client.close();
prefs.edit().putString("url",endpoint).putString("token",token.getText().toString().trim()).apply();
createClient(); append("配置已保存到测试应用私有存储");
}).setNegativeButton("取消",null).show();
}
@Override
protected void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
tts = null;
}
private void append(String message) {
Log.i(TAG,message);
runOnUiThread(() -> { if(!isDestroyed()) log.append(message+"\n"); });
}
@Override public void onDestroy() {
batch=false;
if(client!=null) client.close();
if(engine!=null) engine.close();
super.onDestroy();
}
}
}
@@ -1,12 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true">
<LinearLayout
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:orientation="vertical"
android:padding="16dp">
<TextView android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="语音合成测试:SDK / 引擎在线 / 引擎离线" android:textSize="18sp" />
<Spinner android:id="@+id/synthesis_mode" android:layout_width="match_parent"
android:layout_height="48dp" />
<Button android:id="@+id/btn_engine_config" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="系统引擎设置(语音包及引擎在线配置)" />
<Button android:id="@+id/btn_online_config" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="配置 SDK 在线服务地址与令牌" />
<Button android:id="@+id/btn_online_error" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="在线错误用例:超出 300 字限制" />
<EditText
android:id="@+id/text_input"
android:layout_width="match_parent"
@@ -73,13 +84,13 @@
<TextView
android:id="@+id/log_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_height="240dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:background="#11000000"
android:padding="8dp"
android:scrollbars="vertical"
android:textIsSelectable="true"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</ScrollView>
+12 -2
View File
@@ -7,8 +7,18 @@ pluginManagement {
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
google { content { excludeGroup 'com.ttstd' } }
mavenCentral { content { excludeGroup 'com.ttstd' } }
maven {
name = 'gitea'
url = uri('https://gitea.ttstd.com/api/packages/maven/maven')
content { includeGroup 'com.ttstd' }
credentials(org.gradle.api.credentials.HttpHeaderCredentials) {
name = 'Authorization'
value = "token ${providers.gradleProperty('giteaToken').orElse(providers.environmentVariable('GITEA_TOKEN')).getOrElse('')}"
}
authentication { header(org.gradle.authentication.http.HttpHeaderAuthentication) }
}
}
}