Docs menu
SDKs

Android SDK

View Markdown

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'

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 Prototypepublic static SpeechEval createInstance(Context context, SetupListener listener)
DescriptionCreate evaluation class object
Input Parameterscontext: Context object
listener: Callback after model copy completion
Return ValueNone
UsageCreate evaluation class object

setListener

Function Prototypepublic void setListener(Listener listener)
DescriptionSet Listener
Input Parameterslistener: Listener object
Return ValueNone
UsageSet Listener

setLangType

Function Prototypepublic void setLangType(LangType langType)
DescriptionSet language
Input ParameterslangType: Language code
Return ValueNone
UsageSet language

setScale

Function Prototypepublic void setScale(int scale)
DescriptionSet scoring scale
Input Parametersscale: Scoring scale 1-100
Return ValueNone
UsageSet scoring scale

setSampleRate

Function Prototypepublic void setSampleRate(int sampleRate)
DescriptionSet sample rate
Input ParameterssampleRate: Sample rate 16000
Return ValueNone
UsageSet sample rate

setLooseness

Function Prototypepublic void setLooseness(int looseness)
DescriptionSet scoring flexibility
Input Parameterslooseness: Scoring flexibility 0-9
Return ValueNone
UsageSet scoring flexibility

setConnectTimeout

Function Prototypepublic void setConnectTimeout(int timeout)
DescriptionSet connection timeout
Input Parameterstimeout: Timeout 1-60
Return ValueNone
UsageSet connection timeout

setResponseTimeout

Function Prototypepublic void setResponseTimeout(int timeout)
DescriptionSet response timeout
Input Parameterstimeout: Timeout 1-60
Return ValueNone
UsageSet response timeout

setRatio

Function Prototypepublic void setRatio(float ratio)
DescriptionSet scoring adjustment factor
Input Parametersratio: Adjustment factor 0.8-1.5
Return ValueNone
UsageThis coefficient adjusts scores between 30-90 (on a 100-point scale) up or down, other ranges are unchanged
ratio >1.0 adjusts scores up, more adjustment closer to 75
ratio <1.0 adjusts scores down, more adjustment closer to 75
ratio =1.0 no adjustment

setSaveAudio

Function Prototypepublic void setSaveAudio(boolean saveAudio)
DescriptionSet whether to save recorded audio
Input ParameterssaveAudio: true to save local audio, false to not save
Return ValueNone
UsageSet whether to save recorded audio

setModelPath

Function Prototypepublic void setSaveAudio(String modelPath)
DescriptionSet offline model loading path
Input ParametersmodelPath pass directory path, if not passed use getExternalFilesDir(null).getPath()/model
Return ValueNone
UsageMust be an accessible operation path which is the path where the model file is stored and extracted

setMaxPrefixSilenceMs

Function Prototypepublic void setMaxPrefixSilenceMs(int maxPrefixSilenceMs)
DescriptionSet voice leading silence detection threshold (milliseconds)
Input ParametersmaxPrefixSilenceMs: Range [0-30000]
Return ValueNone
UsageIf the silence duration after voice start exceeds this threshold, a Warning event will be returned

setMaxSuffixSilenceMs

Function Prototypepublic void setMaxSuffixSilenceMs(int maxSuffixSilenceMs)
DescriptionSet voice trailing silence detection threshold (milliseconds)
Input ParametersmaxSuffixSilenceMs: Range [0-30000]
Return ValueNone
UsageIf the trailing silence duration exceeds this threshold, the evaluation will automatically end

setPrecision

Function Prototypepublic void setPrecision(int precision)
DescriptionSets the scoring precision
Input Parametersprecision: 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 ValueNone
Usage NotesSet the precision based on the scoring accuracy required by the business

setConnti

Function Prototypepublic void setConnti(int connti)
DescriptionEnable liaison and loss of plosion detection, default is 0, English only
Input Parametersconnti 0 to disable
connti 1 to enable
Return ValueNone
UsageDefault 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 Prototypepublic void setServerAPI(String serverAPI)
DescriptionSet the online server address, requesting the specified domain server
Input ParameterserverAPI, the provided domain name
Return ValueNone
InstructionsNeeds to be set before initialization, if not set, the general domain will be used

setTestServerAPI

Function Prototypepublic void setTestServerAPI(String testServerAPI)
DescriptionSet the online test server address, requesting the specified domain server
Input ParametertestServerAPI, the provided domain name
Return ValueNone
InstructionsNeeds to be set before initialization, if not set, the general domain will be used

setI18n

Function Prototypepublic void setI18n(SpeechEval.I18n i18n)
DescriptionSet the internationalization return language type. The prompt information (warning and error) will be returned according to the set language type.
Input Parameteri18n, language type parameter, supports enumeration EN, ZH, None. EN: English, ZH: Chinese, None: SDK will use the system language
Return ValueNone
InstructionsNeeds 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 Prototypepublic ErrorCodes.ErrorCode init(String appId, String appSecret, String userId)
DescriptionInitialize service
Input ParametersuserId: User identity for statistics
Return ValueError code object, containing error code and message
UsageInitialize service

setParamsJson

Function Prototypepublic void setParamsJson(JSONObject json)
DescriptionSet parameters object
Input ParametersNone
Return ValueJSON object
UsageUsed to set JSON parameters

createRecorder

Function Prototypepublic Recorder createRecorder()
DescriptionGet Recorder object
Input ParametersNone
Return ValueRecorder object
UsageWhen using SDK recording, get Recorder object to pass into start() method

start

Function Prototypepublic ErrorCodes.ErrorCode start(Recorder recorder)
DescriptionStart evaluation (using SDK recording)
Input Parametersrecorder: Recorder object obtained from createRecorder()
Return ValueError code object
UsageStart evaluation (using SDK recording)
Function Prototypepublic ErrorCodes.ErrorCode start(String wavPath)
DescriptionStart evaluation (passing audio file)
Input ParameterswavPath: Audio file path
Return ValueError code object
UsageStart evaluation (passing audio file), automatically sends audio after start, automatically completes evaluation after sending finishes
Function Prototypepublic ErrorCodes.ErrorCode start()
DescriptionStart evaluation (manually send audio packets)
Input ParametersNone
Return ValueError code object
UsageStart evaluation (manually send audio packets), need to call feed() method subsequently to send audio data packets

feed

Function Prototypepublic void feed(byte[] data)
DescriptionManually send audio data packets
Input ParametersAudio data, recommended audio data length per send is 1920 Bytes
Return ValueError code object
UsageAfter calling start(), call repeatedly feed() to pass in audio data

stop

Function Prototypepublic void stop()
DescriptionStop evaluation
Input ParametersNone
Return ValueNone
UsageStop evaluation

cancel

Function Prototypepublic void cancel()
DescriptionCancel evaluation after start
Input ParametersNone
Return ValueNone
UsageCancel evaluation after start, no result returned

destroy

Function Prototypepublic void destroy()
DescriptionRelease evaluation resources
Input ParametersNone
Return ValueNone
UsageGenerally can be called in Activity.onDestroy

update

Function Prototypepublic void update(true, OnUpdateListener listener)
DescriptionManually generate new token
Input Parameterslistener: Callback after update completion
Return ValueNone
UsageGenerally no need to call actively

getExpireTimestamp

Function Prototypepublic long getExpireTimestamp(true)
DescriptionQuery token expiration time
Input ParametersFixed to true
Return ValueUNIX timestamp
UsageToken valid period is 168 hours

SpeechEval.LangType Class

Speech evaluation language

MemberMeaning
enUSEnglish

SpeechEval.Mode Class

Speech evaluation question type

MemberMeaning
WORDWord type
SENTENCESentence type
CHAPTERChapter type
PHONEMEPhoneme type
QAQuestion & Answer type
TOPICPicture description/oral essay type
RETELLRetell type
WORDCHECKWord correction type
SENTENCECHECKSentence correction type
EXTCHOICEExtended choice type

SpeechEval.Listener Class

Speech evaluation callback interface

onResult

Function Prototypevoid onResult(String result)
DescriptionEvaluation result callback method
Input Parameters (Callback Return)result - Evaluation result
Return ValueNone
UsageEvaluation result callback method

onStartRecording

Function Prototypevoid onStartRecording(String taskId)
DescriptionRecording start callback method
Input Parameters (Callback Return)None
Return ValueNone
UsageRecording start callback method

onStopSending

Function Prototypevoid onStopSending()
DescriptionEvaluation end callback method
Input Parameters (Callback Return)None
Return ValueNone
UsageEvaluation end callback method

onGetAudio

Function Prototypevoid onGetAudio(byte[] data)
DescriptionReturns recorded audio in real-time when evaluating using recording mode
Input Parameters (Callback Return)data: Audio data
Return ValueNone
UsageReturns audio data in real-time when evaluating using recording mode

onGetVolume

Function Prototypevoid onGetVolume(double volume)
DescriptionReturns volume in real-time when evaluating using recording mode
Input Parameters (Callback Return)volume: Volume level
Return ValueNone
UsageReturns volume level in real-time when evaluating using recording mode

onError

Function Prototypevoid onError(String taskId,String code, String msg)
DescriptionCallback when evaluation error occurs
Input Parameters (Callback Return)code: Error code
msg: Error message
Return ValueNone
UsageCallback when evaluation error occurs, no result in onResult

onWarning

Function Prototypevoid onWarning(String taskId,String code, String msg)
DescriptionCallback when evaluation warning occurs
Input Parameters (Callback Return)code: Error code
msg: Error message
Return ValueNone
UsageCallback 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

  1. 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.

  1. 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.

  1. What audio formats are supported for speech evaluation?

For supported audio formats, please see the Supported Audio Formats documentation.

  1. Error codes and solutions

For error code explanations, please see the Status Code documentation.

  1. 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.

  1. 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.

  1. 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.

  1. How to resolve libc++_shared.so conflict

Add the following code to your project's build file:

 android {
             packagingOptions {
                            pickFirst 'lib/*/libc++_shared.so'
                     }
         }
  1. 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.**{*;}