初始化 TTS 引擎工程:Android 系统引擎、Go 在线合成服务与测试客户端

- android-engine:TextToSpeechService 引擎,含设置页、语音包导入(SHA-256 校验)与预热
- server:Go CPU 合成服务与部署文件
- test-client:端到端验证客户端
- 模型与语音包不入库,见 models/README.md
This commit is contained in:
tongtong committed 2026-11-23 14:59:46 +08:00
commit 1856de97bc
62 files changed
+3787

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
.gradle/
build/
local.properties
*.apk
*.iml
.idea/
+26
View File
@@ -0,0 +1,26 @@
plugins {
id 'com.android.application'
}
android {
namespace 'com.ttstd.tts.testclient'
compileSdk 37
defaultConfig {
applicationId 'com.ttstd.tts.testclient'
minSdk 23
targetSdk 34
versionCode 1
versionName '0.1.0'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
lint {
abortOnError false
checkReleaseBuilds = false
}
}
@@ -0,0 +1,27 @@
<?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>
<package android:name="com.ttstd.tts.engine" />
</queries>
<application
android:allowBackup="false"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.DeviceDefault.Light">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,221 @@
package com.ttstd.tts.testclient;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
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.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 java.util.Locale;
import java.util.Set;
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 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);
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) {
}
};
rateBar.setOnSeekBarChangeListener(labels);
pitchBar.setOnSeekBarChangeListener(labels);
updateLabels();
findViewById(R.id.btn_speak).setOnClickListener(v -> speak());
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);
}
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()));
try {
getPackageManager().getPackageInfo(ENGINE, 0);
appendLog("getPackageInfo(" + ENGINE + ") 可见");
} catch (Exception e) {
appendLog("getPackageInfo(" + ENGINE + ") 不可见: " + e.getClass().getSimpleName());
}
}
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() {
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 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 updateLabels() {
rateLabel.setText(getString(R.string.rate_label, rate()));
pitchLabel.setText(getString(R.string.pitch_label, 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");
}
@Override
protected void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
tts = null;
}
super.onDestroy();
}
}
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_text"
android:inputType="text"
android:text="你好,现在是北京时间十二点整" />
<TextView
android:id="@+id/rate_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/rate_label" />
<SeekBar
android:id="@+id/rate_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="150"
android:progress="50" />
<TextView
android:id="@+id/pitch_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pitch_label" />
<SeekBar
android:id="@+id/pitch_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="150"
android:progress="50" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal">
<Button
android:id="@+id/btn_speak"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/action_speak" />
<Button
android:id="@+id/btn_stop"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/action_stop" />
<Button
android:id="@+id/btn_sweep"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/action_sweep" />
</LinearLayout>
<TextView
android:id="@+id/log_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:background="#11000000"
android:padding="8dp"
android:scrollbars="vertical"
android:textIsSelectable="true"
android:textSize="12sp" />
</LinearLayout>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TTS 引擎测试</string>
<string name="hint_text">朗读内容</string>
<string name="rate_label">语速 %1$.2f</string>
<string name="pitch_label">音调 %1$.2f</string>
<string name="action_speak">朗读</string>
<string name="action_stop">停止</string>
<string name="action_sweep">参数遍历</string>
</resources>
+9
View File
@@ -0,0 +1,9 @@
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.2'
}
}
+3
View File
@@ -0,0 +1,3 @@
org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
android.useAndroidX=false
android.suppressUnsupportedCompileSdk=37.0
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
#Sat Oct 11 20:25:09 CST 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
+84
View File
@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+16
View File
@@ -0,0 +1,16 @@
pluginManagement {
repositories {
google()
mavenCentral()
}
}
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}
rootProject.name = "TTStdTtsTestClient"
include ':app'