I. Integration Steps
1. Add aar dependency
Put the speech-eval-sdk.aar file into the libs directory of your project, modify the build.gradle file of the app module, and add the aar file and okhttp as dependencies.
implementation fileTree(dir: "libs", include: ["*.jar","*.aar"])
implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.8' //Add okhttp here. If your project is older, you can use version 3.14.2
implementation 'commons-codec:commons-codec:1.15'2. Add app-related permissions
Modify the AndroidManifest.xml file
<!--Recording permission-->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!--Network permission-->
<uses-permission android:name="android.permission.INTERNET" />3. Calling steps/sample code
① Get recording permission
boolean hasAudioPermission;
ActivityResultLauncher<String> permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), result -> {
hasAudioPermission = result; //result is true means recording permission is granted
});
permissionLauncher.launch(Manifest.permission.RECORD_AUDIO);② Instance of Initialize the engine
SpeechEval eval = SpeechEval.createInstance(activity);
eval.setSampleRate(16000); //Set sample rate, only 16000 supported
eval.setListener(getListener()); //Set callback listener
//Configure English evaluation, if available, set OralOnLine, otherwise leave blank or set to None
eval.setInitLanguageEn(SpeechEval.InitSettingOnline.OralOnLine);
//Configuring Japanese evaluation only supports OralOnLine online configuration, not offline. If this language is not available, do not add this method or set it to None.
evalEn.setInitLanguageJa(SpeechEval.InitSettingOnline.OralOnLine);
eval.setServerAPI("api.soe.dolphin-ai.jp");
eval.setI18n(SpeechEval.I18n.EN);
//Check the engineInitState callback method for initialization status
eval.init(appId, appSecret, userId);
private SpeechEval.Listener getListener() {
return new SpeechEval.Listener() {
@Override
public void onWsStart(String taskId) {
//Callback when online evaluation ws is established
}
@Override
public void onResult(String result, boolean online) {
// Evaluation result callback
// online is always true
}
@Override
public void onStartRecording() {
//Recording start callback
}
@Override
public void onStopSending() {
//Recording stop callback
}
@Override
public void onGetAudio(byte[] data) {
//For recording mode, returns real-time audio
}
@Override
public void onGetVolume(double volume) {
//Real-time volume callback
}
@Override
public void onWarning(String taskId, String code, String msg) {
//Warning info, handle based on business needs
}
@Override
public void onError(String taskId, String code, String msg) {
//Evaluation error callback
}
@Override
public void onRealtimeResult(String result) {
// Enable realtime to receive updates for English sentence, chapter, and freedom tasks.
}
@Override
public void onSaveAudioFile(String localPath) {
// This method is called if setSaveAudio(true) is set
}
@Override
public void engineInitState(String code, String msg) {
if ("00000".equals(code)) {
//Initialization succeeded
}else {
// Initialization failed
}
}
};
}The engineInitState callback method status codes:
Online
"00000","success"
"13010", "Missing network permission"
"13011", "No network connection"
"10002", "Parameter error"
"11011", "Signature error"
"11012", "Invalid appid"
"11013", "Appid does not exist"
"11014", "Error generating token"
"11015", "Invalid current time"③ Set parameters
Evaluation parameters
Please refer to the Common Parameters: Evaluation Parameters documentation.
- Use the
eval.setKEY(VALUE);method to set evaluation parameters - If required parameters are missing or out of range, an error code and error message will be returned in
onError - If optional parameters are missing, the default value will be used; if out of range, the default value will be used and an error code and error message will be returned in
onWarning
Question type parameters
Please refer to the corresponding question type's Interface Parameters documentation.
Sample code
/**
* Set or modify before evaluation, parameters with default values can be left unset
*
*/
eval.setLangType(SpeechEval.LangType.enUS); //Set language for evaluation, no default (required), must be set before evaluation
eval.setSampleRate(16000); //Set sample rate, only 16000 supported, required
eval.setAudioUrl(false); //Set whether to save audio (server side), default is false (do not save)
eval.setSaveAudio(true); //Set whether to save audio (mobile side), default false, do not save. Can also save data based on real-time audio fragments returned by onGetVolume
eval.setAudioSavePath("/sdcard/xxx/abc.wav"); //Set audio save path, takes effect when setSaveAudio is true
eval.setScale(100); //Scoring scale, default is 100
eval.setRatio(1.0f); //Set scoring adjustment factor, range 0.8-1.5, default 1.0
eval.setLooseness(4); //Set scoring flexibility, range 0-9, default 4
//Build question type related parameter JSON (e.g. word type)
JSONObject jsonObject = new JSONObject();
SpeechEval.Mode mode = SpeechEval.Mode.WORD;
String text = "good morning";
try {
jsonObject.put("mode", mode);
jsonObject.put("refText", text);
} catch (JSONException e) {
e.printStackTrace();
}
eval.setParamsJson(jsonObject);④ Start/stop evaluation
Start evaluation (recording mode)
Recorder recorder = eval.createRecorder();
eval.start(recorder);
//Start receiving audio via microphone
// ...
//After receiving, manually stop recording to complete evaluation
eval.stop();Start evaluation (sending audio file mode)
//Start
String wavePath = "/sdcard/xxx/abc.wav"
eval.start(wavePath); //Pass in WAV or PCM audio data, requires 16000Hz, 16Bit, mono audio file
//Automatically read and send audio file, stop automatically after completion⑤ Handle evaluation results
Refer to ② Create evaluation class object to handle evaluation results in the listener
⑥ Release evaluation resources
//Generally can be called in Activity.onDestroy
eval.destroy();4. Obfuscation mechanism
//If obfuscation is needed, exclude the SDK from obfuscation
-keep class com.zhiyan.**{*;}II. Interface Documentation
SpeechEval class
Main speech evaluation class
createInstance
| Function Prototype | public static SpeechEval createInstance(Context context, SetupListener listener) |
|---|---|
| Description | Create evaluation class object |
| Input Parameters | context: Context object listener: Callback after model copy completion |
| Return Value | None |
| Usage | Create evaluation class object |
setListener
| Function Prototype | public void setListener(Listener listener) |
|---|---|
| Description | Set Listener |
| Input Parameters | listener: Listener object |
| Return Value | None |
| Usage | Set Listener |
setLangType
| Function Prototype | public void setLangType(LangType langType) |
|---|---|
| Description | Set language |
| Input Parameters | langType: Language code |
| Return Value | None |
| Usage | Set language |
setScale
| Function Prototype | public void setScale(int scale) |
|---|---|
| Description | Set scoring scale |
| Input Parameters | scale: Scoring scale 1-100 |
| Return Value | None |
| Usage | Set scoring scale |
setSampleRate
| Function Prototype | public void setSampleRate(int sampleRate) |
|---|---|
| Description | Set sample rate |
| Input Parameters | sampleRate: Sample rate 16000 |
| Return Value | None |
| Usage | Set sample rate |
setLooseness
| Function Prototype | public void setLooseness(int looseness) |
|---|---|
| Description | Set scoring flexibility |
| Input Parameters | looseness: Scoring flexibility 0-9 |
| Return Value | None |
| Usage | Set scoring flexibility |
setConnectTimeout
| Function Prototype | public void setConnectTimeout(int timeout) |
|---|---|
| Description | Set connection timeout |
| Input Parameters | timeout: Timeout 1-60 |
| Return Value | None |
| Usage | Set connection timeout |
setResponseTimeout
| Function Prototype | public void setResponseTimeout(int timeout) |
|---|---|
| Description | Set response timeout |
| Input Parameters | timeout: Timeout 1-60 |
| Return Value | None |
| Usage | Set response timeout |
setRatio
| Function Prototype | public void setRatio(float ratio) |
|---|---|
| Description | Set scoring adjustment factor |
| Input Parameters | ratio: Adjustment factor 0.8-1.5 |
| Return Value | None |
| Usage | This coefficient adjusts scores between 30-90 (on a 100-point scale) up or down, other ranges are unchangedratio >1.0 adjusts scores up, more adjustment closer to 75ratio <1.0 adjusts scores down, more adjustment closer to 75ratio =1.0 no adjustment |
setSaveAudio
| Function Prototype | public void setSaveAudio(boolean saveAudio) |
|---|---|
| Description | Set whether to save recorded audio |
| Input Parameters | saveAudio: true to save local audio, false to not save |
| Return Value | None |
| Usage | Set whether to save recorded audio |
setModelPath
| Function Prototype | public void setSaveAudio(String modelPath) |
|---|---|
| Description | Set offline model loading path |
| Input Parameters | modelPath pass directory path, if not passed use getExternalFilesDir(null).getPath()/model |
| Return Value | None |
| Usage | Must be an accessible operation path which is the path where the model file is stored and extracted |
setMaxPrefixSilenceMs
| Function Prototype | public void setMaxPrefixSilenceMs(int maxPrefixSilenceMs) |
|---|---|
| Description | Set voice leading silence detection threshold (milliseconds) |
| Input Parameters | maxPrefixSilenceMs: Range [0-30000] |
| Return Value | None |
| Usage | If the silence duration after voice start exceeds this threshold, a Warning event will be returned |
setMaxSuffixSilenceMs
| Function Prototype | public void setMaxSuffixSilenceMs(int maxSuffixSilenceMs) |
|---|---|
| Description | Set voice trailing silence detection threshold (milliseconds) |
| Input Parameters | maxSuffixSilenceMs: Range [0-30000] |
| Return Value | None |
| Usage | If the trailing silence duration exceeds this threshold, the evaluation will automatically end |
setPrecision
| Function Prototype | public void setPrecision(int precision) |
|---|---|
| Description | Sets the scoring precision |
| Input Parameters | precision: Default is 0, supports only 0, 0.1, 0.25, 0.5, 1. If the set value is not one of these, it is treated as 0 |
| Return Value | None |
| Usage Notes | Set the precision based on the scoring accuracy required by the business |
setConnti
| Function Prototype | public void setConnti(int connti) |
|---|---|
| Description | Enable liaison and loss of plosion detection, default is 0, English only |
| Input Parameters | connti 0 to disable connti 1 to enable |
| Return Value | None |
| Usage | Default is 0, no this function can be left unset or set to 0, set to 1 to enable liaison and loss of plosion detection |
setServerAPI
| Function Prototype | public void setServerAPI(String serverAPI) |
|---|---|
| Description | Set the online server address, requesting the specified domain server |
| Input Parameter | serverAPI, the provided domain name |
| Return Value | None |
| Instructions | Needs to be set before initialization, if not set, the general domain will be used |
setTestServerAPI
| Function Prototype | public void setTestServerAPI(String testServerAPI) |
|---|---|
| Description | Set the online test server address, requesting the specified domain server |
| Input Parameter | testServerAPI, the provided domain name |
| Return Value | None |
| Instructions | Needs to be set before initialization, if not set, the general domain will be used |
setI18n
| Function Prototype | public void setI18n(SpeechEval.I18n i18n) |
|---|---|
| Description | Set the internationalization return language type. The prompt information (warning and error) will be returned according to the set language type. |
| Input Parameter | i18n, language type parameter, supports enumeration EN, ZH, None. EN: English, ZH: Chinese, None: SDK will use the system language |
| Return Value | None |
| Instructions | Needs to be set before initialization. If this method is not set or set to None, the system language will be used. If the system language is Chinese, Chinese prompt information will be returned; for other languages, English prompt information will be returned. |
init
| Function Prototype | public ErrorCodes.ErrorCode init(String appId, String appSecret, String userId) |
|---|---|
| Description | Initialize service |
| Input Parameters | userId: User identity for statistics |
| Return Value | Error code object, containing error code and message |
| Usage | Initialize service |
setParamsJson
| Function Prototype | public void setParamsJson(JSONObject json) |
|---|---|
| Description | Set parameters object |
| Input Parameters | None |
| Return Value | JSON object |
| Usage | Used to set JSON parameters |
createRecorder
| Function Prototype | public Recorder createRecorder() |
|---|---|
| Description | Get Recorder object |
| Input Parameters | None |
| Return Value | Recorder object |
| Usage | When using SDK recording, get Recorder object to pass into start() method |
start
| Function Prototype | public ErrorCodes.ErrorCode start(Recorder recorder) |
|---|---|
| Description | Start evaluation (using SDK recording) |
| Input Parameters | recorder: Recorder object obtained from createRecorder() |
| Return Value | Error code object |
| Usage | Start evaluation (using SDK recording) |
| Function Prototype | public ErrorCodes.ErrorCode start(String wavPath) |
|---|---|
| Description | Start evaluation (passing audio file) |
| Input Parameters | wavPath: Audio file path |
| Return Value | Error code object |
| Usage | Start evaluation (passing audio file), automatically sends audio after start, automatically completes evaluation after sending finishes |
| Function Prototype | public ErrorCodes.ErrorCode start() |
|---|---|
| Description | Start evaluation (manually send audio packets) |
| Input Parameters | None |
| Return Value | Error code object |
| Usage | Start evaluation (manually send audio packets), need to call feed() method subsequently to send audio data packets |
feed
| Function Prototype | public void feed(byte[] data) |
|---|---|
| Description | Manually send audio data packets |
| Input Parameters | Audio data, recommended audio data length per send is 1920 Bytes |
| Return Value | Error code object |
| Usage | After calling start(), call repeatedly feed() to pass in audio data |
stop
| Function Prototype | public void stop() |
|---|---|
| Description | Stop evaluation |
| Input Parameters | None |
| Return Value | None |
| Usage | Stop evaluation |
cancel
| Function Prototype | public void cancel() |
|---|---|
| Description | Cancel evaluation after start |
| Input Parameters | None |
| Return Value | None |
| Usage | Cancel evaluation after start, no result returned |
destroy
| Function Prototype | public void destroy() |
|---|---|
| Description | Release evaluation resources |
| Input Parameters | None |
| Return Value | None |
| Usage | Generally can be called in Activity.onDestroy |
update
| Function Prototype | public void update(true, OnUpdateListener listener) |
|---|---|
| Description | Manually generate new token |
| Input Parameters | listener: Callback after update completion |
| Return Value | None |
| Usage | Generally no need to call actively |
getExpireTimestamp
| Function Prototype | public long getExpireTimestamp(true) |
|---|---|
| Description | Query token expiration time |
| Input Parameters | Fixed to true |
| Return Value | UNIX timestamp |
| Usage | Token valid period is 168 hours |
SpeechEval.LangType Class
Speech evaluation language
| Member | Meaning |
|---|---|
| enUS | English |
SpeechEval.Mode Class
Speech evaluation question type
| Member | Meaning |
|---|---|
| WORD | Word type |
| SENTENCE | Sentence type |
| CHAPTER | Chapter type |
| PHONEME | Phoneme type |
| QA | Question & Answer type |
| TOPIC | Picture description/oral essay type |
| RETELL | Retell type |
| WORDCHECK | Word correction type |
| SENTENCECHECK | Sentence correction type |
| EXTCHOICE | Extended choice type |
SpeechEval.Listener Class
Speech evaluation callback interface
onResult
| Function Prototype | void onResult(String result) |
|---|---|
| Description | Evaluation result callback method |
| Input Parameters (Callback Return) | result - Evaluation result |
| Return Value | None |
| Usage | Evaluation result callback method |
onStartRecording
| Function Prototype | void onStartRecording(String taskId) |
|---|---|
| Description | Recording start callback method |
| Input Parameters (Callback Return) | None |
| Return Value | None |
| Usage | Recording start callback method |
onStopSending
| Function Prototype | void onStopSending() |
|---|---|
| Description | Evaluation end callback method |
| Input Parameters (Callback Return) | None |
| Return Value | None |
| Usage | Evaluation end callback method |
onGetAudio
| Function Prototype | void onGetAudio(byte[] data) |
|---|---|
| Description | Returns recorded audio in real-time when evaluating using recording mode |
| Input Parameters (Callback Return) | data: Audio data |
| Return Value | None |
| Usage | Returns audio data in real-time when evaluating using recording mode |
onGetVolume
| Function Prototype | void onGetVolume(double volume) |
|---|---|
| Description | Returns volume in real-time when evaluating using recording mode |
| Input Parameters (Callback Return) | volume: Volume level |
| Return Value | None |
| Usage | Returns volume level in real-time when evaluating using recording mode |
onError
| Function Prototype | void onError(String taskId,String code, String msg) |
|---|---|
| Description | Callback when evaluation error occurs |
| Input Parameters (Callback Return) | code: Error code msg: Error message |
| Return Value | None |
| Usage | Callback when evaluation error occurs, no result in onResult |
onWarning
| Function Prototype | void onWarning(String taskId,String code, String msg) |
|---|---|
| Description | Callback when evaluation warning occurs |
| Input Parameters (Callback Return) | code: Error code msg: Error message |
| Return Value | None |
| Usage | Callback when evaluation warning occurs, result in onResult |
III. Response Results
Please refer to the corresponding question type's Interface Parameters documentation.
IV. Status Code Table
Please refer to the Status Code documentation.
V. FAQ
- What is the minimum supported Android system version?
Answer: The current Android SDK version supports Android 4.4 and above. Cross-platform solutions like React-Native are currently not supported and need to be packaged manually.
- What application platforms does speech evaluation support?
Currently speech evaluation supports: Android, iOS, Web, Mini Programs, Linux, Windows, Dictionary Pens, RTOS and other application platforms.
- What audio formats are supported for speech evaluation?
For supported audio formats, please see the Supported Audio Formats documentation.
- Error codes and solutions
For error code explanations, please see the Status Code documentation.
- Supported question types, text/audio length limits, results and field meanings for speech evaluation
For supported question types, text/audio length limits by the speech engine, please see the Question Types and Parameter Introduction documentation.
- Why is the audioUrl field missing or blank in the result?
For online evaluation, you need to pass audioUrl=true before evaluation for the audioUrl to be returned in the result.
For offline evaluation, audioUrl will not be returned regardless of audioUrl=true or false.
- How long are evaluation audios stored for?
Audio is retained for 30 days by default, it is recommended to download it to your server for long-term preservation.
- How to resolve libc++_shared.so conflict
Add the following code to your project's build file:
android {
packagingOptions {
pickFirst 'lib/*/libc++_shared.so'
}
}- If code obfuscation is enabled, evaluation does not work properly
Check if the following rule is added in the proguard-rules.pro file:
-keep class com.zhiyan.**{*;}