Docs menu
Docs

Harmony SDK

View Markdown

I. Integration Steps

1. Integration Method

1.1 Add HAR Dependency (Local Integration)

Place speech_eval_sdk.har into the libs directory of your project, then enter that directory to install:

Command: ohpm install speech_eval_sdk.har

Include the following dependencies:

ohpm install @ohos/crypto-js

1.2 Integration via ohpem Repository (Remote Integration)

Command: ohpm install speech_eval_sdk

Include the following dependencies:

ohpm install @ohos/crypto-js

Add the following to the module.json5 file in your project:

    "requestPermissions": [
      {
        "name": "ohos.permission.MICROPHONE",
        "reason": "$string:麦克风权限",
        "usedScene": {
          "abilities": [
            "FormAbility"
          ],
          "when":"always"
        }
      },
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.READ_MEDIA",
        "reason": "$string:读取权限",
        "usedScene": {
          "when": "always"
        }
      }
    ]

3. Call Steps/Example Code

Evaluation Flowchart

① Request Permissions

async function requestPermissions() {
  const permissions: Array<Permissions> = [
    'ohos.permission.INTERNET',//Allow use of Internet network
    'ohos.permission.READ_MEDIA',//Allow app to read media file information from external storage
    'ohos.permission.WRITE_MEDIA',//Allow app to read and write media file information from external storage
    'ohos.permission.MICROPHONE',//Allow app to use the microphone
  ];
  let atManager = abilityAccessCtrl.createAtManager();

  await atManager.requestPermissionsFromUser(context, permissions).then((data) => {
    console.log('TAG', `Request permissions succeed, data is: ${data}`);
  }).catch((error: Error) => {
    console.log('TAG', `Request permissions failed, error is: ${error}`);
  });
}

② Initialize Engine Instance

eval: SpeechEval = SpeechEval.getInstance(context)
  // Set listener
  const listeners: Listener = {
    onWsStart: (taskId: string): void => {
      // Callback when online evaluation WebSocket connection is established
    },
    onResult: (result: string, online: boolean): void => {
      // Callback for evaluation result
    },
    onStartRecording: (): void => {
      // Callback when recording starts
    },
    onStopSending: (): void => {
      // Callback when recording stops
    },
    onGetAudio: (data: ArrayBuffer | undefined): void => {
      // Return real-time audio when using recording mode
    },
    onGetVolume: (volume: number): void => {
      // Callback for real-time volume information
    },
    onWarning: (taskId: string, code: string, msg: string): void => {
      // Handle warnings and alerts as per your business needs
    },
    onError: (taskId: string, code: string, msg: string): void => {
      // Callback for evaluation errors
    },
    onRealtimeResult: (msg: string): void => {
      // Enable realtime to receive updates for English sentence, chapter, and freedom tasks.
    },
    onSaveAudioFile: (localPath: string): void => {
      // This method will be called if setSaveAudio(true) is set
    },
    engineInitState: (code: string, msg: string): void => {
      if (code === "00000") {
        promptAction.showToast({
          message: "Initialization successful"
        })
      } else {
        promptAction.showToast({
          message: code + msg
        })
      }
    }
  };
eval.setListener(listeners); // Set callback listener
// Configure English evaluation, if this language is available, set to OralOnLine, otherwise can be left unset or set to None
eval.setInitLanguageEn(InitSettingOnline.OralOnLine);
// Check initialization status in the engineInitState callback method
// userId, suggested to be set to distinguish different users
eval.init(appId, appSecret, userId);

Initialization status callback method engineInitState corresponding status codes:

Online:
"00000","success"
"13010", "Network permission missing"
"13011", "No network connection"
"10002", "Parameter error"
"11011", "Signature error"
"11012", "App ID unavailable"
"11013", "App ID does not exist"
"11014", "Error generating token"
"11015", "Illegal current time"

③ Set Parameters

Evaluation Parameters

Please refer to the Common Parameters: Evaluation Parameters documentation.

  • Use eval.setKEY(VALUE); to set evaluation parameters
  • Required parameters, if missing or out of range, will return error codes and messages in onError
  • Optional parameters, if missing, will use default values; if out of range, default values will be applied and an error code/message will be returned in onWarning
Question type parameters

Please refer to the corresponding question type's Interface Parameters documentation.

Example Code
/**
 * Set or modify before evaluation, parameters with default values can be omitted
 *
 */
eval.setLangType(SpeechEval.LangType.enUS);  // Set language to evaluate, no default value (required), must be set before evaluation
eval.setSampleRate(16000);  // Set sample rate, only supports 16000, required
eval.setAudioUrl(false);  // Set whether to save audio (server-side), defaults to false (not saved)
eval.setSaveAudio(true);  // Set whether to save audio (mobile), default false, does not save. You can also save data based on the real-time segments returned by onGetVolume
eval.setAudioSavePath("/sdcard/xxx/abc.pcm");  // Set audio save path, effective when setSaveAudio is true
eval.setScale(100);     // Set score scale, defaults to 100
eval.setRatio(1);   // Set score adjustment factor, range 0.8-1.5, defaults to 1.0
eval.setLooseness(4);  // Set score leniency, range 0-9, default is 4
eval.setClientData("1111");  // Set custom parameters, customers can pass in their required parameters, will be returned in the response as the clientData field, other types should be converted to string type

// Construct topic parameters JSON (example with word type)
 const paramsJson: ParamsJson = {
      mode: this.mode.toString(),
      refText: this.reTxet
    }
 eval.setParamsJson(paramsJson);

④ Start/Stop Evaluation

Start Evaluation (Recording Method)

eval.start();
// Now the microphone will start receiving audio
// ...
// After receiving is complete, manually stop recording to complete the evaluation
eval.stop();

Start Evaluation (Send Audio File Method)

// Start
let Path = "/sdcard/xxx/abc.pcm"
eval.startPath(Path);  // Pass PCM format audio data, requires 16000Hz, 16Bit, mono audio file
// Automatically reads the audio file and sends it, stops evaluation automatically after completion

⑤ Handle evaluation results

Refer to ② Create evaluation class object to handle evaluation results in the listener

⑥ Release Evaluation Resources

eval.destroy();

4. Obfuscation Mechanism

// If obfuscation is needed, exclude SDK from obfuscation

II. API Documentation

SpeechEval Class

Main class for speech evaluation

createInstance

Function Prototypepublic static getInstance(context: Context): SpeechEval
FunctionalityCreate an evaluation class object
Input Parameterscontext: Context object
Return ValueNone
Usage InstructionsCreate an evaluation class object

setListener

Function Prototypepublic setListener(listener: Listener): void
FunctionalitySet Listener
Input Parameterslistener: Listener object
Return ValueNone
Usage InstructionsSet Listener

setLangType

Function PrototypesetLangType(langType: LangType)
FunctionalitySet language type
Input ParameterslangType: Language code
Return ValueNone
Usage InstructionsSet language type

setScale

Function PrototypesetScale(scale: number)
FunctionalitySet scoring scale
Input Parametersscale: Scoring scale 1-100
Return ValueNone
Usage InstructionsSet scoring scale

setSampleRate

Function Prototypepublic void setSampleRate(int sampleRate)
FunctionalitySet sampling rate
Input ParameterssampleRate: Sampling rate 16000
Return ValueNone
Usage InstructionsSet sampling rate

setLooseness

Function Prototypepublic void setLooseness(int looseness)
FunctionalitySet scoring leniency
Input Parameterslooseness: Scoring leniency 0-9
Return ValueNone
Usage InstructionsSet scoring leniency

setConnectTimeout

Function Prototypepublic void setConnectTimeout(int timeout)
FunctionalitySet connection timeout
Input Parameterstimeout: Timeout in seconds 1-60
Return ValueNone
Usage InstructionsSet connection timeout

setResponseTimeout

Function Prototypepublic void setResponseTimeout(int timeout)
FunctionalitySet response timeout
Input Parameterstimeout: Timeout in seconds 1-60
Return ValueNone
Usage InstructionsSet response timeout

setRatio

Function Prototypepublic void setRatio(float ratio)
FunctionalitySet score adjustment factor
Input Parametersratio: Score adjustment factor 0.8-1.5
Return ValueNone
Usage InstructionsThis factor adjusts scores between 30-90 (out of 100), other scores remain unchanged
ratio >1.0 adjusts scores upwards, the closer to 75, the higher the adjustment
ratio <1.0 adjusts scores downwards, the closer to 75, the higher the adjustment
ratio =1.0 does not adjust scores

setSaveAudio

Function Prototypepublic void setSaveAudio(boolean saveAudio)
FunctionalitySet whether to save recording audio
Input ParameterssaveAudio: true for saving local audio, false for not saving
Return ValueNone
Usage InstructionsSet whether to save recording audio

setModelPath

Function Prototypepublic void setSaveAudio(String modelPath)
FunctionalitySet offline model loading path
Input ParametersmodelPath: Path to the directory where the model files are stored and unzipped
Return ValueNone
Usage InstructionsMust be an accessible path. Path where the model files are stored and unzipped

setMaxPrefixSilenceMs

Function Prototypepublic void setMaxPrefixSilenceMs(int maxPrefixSilenceMs)
FunctionalitySet the threshold for detecting silence before speech (milliseconds)
Input ParametersmaxPrefixSilenceMs: Range [0-30000]
Return ValueNone
Usage InstructionsIf the silence duration exceeds this threshold, a single Warning event will be returned. Setting to 0 means no silence detection at the beginning, no Warning events returned

setMaxSuffixSilenceMs

Function Prototypepublic void setMaxSuffixSilenceMs(int maxSuffixSilenceMs)
FunctionalitySet the threshold for detecting silence after speech (milliseconds)
Input ParametersmaxSuffixSilenceMs: Range [0-30000]
Return ValueNone
Usage InstructionsIf the silence duration at the end of the sentence exceeds this threshold, the evaluation will end automatically. Setting to 0 means no silence detection at the end

setPrecision

Function Prototypepublic void setPrecision(String precision)
FunctionalitySet scoring precision
Input Parametersprecision: Defaults to 0, only supports 0, 0.1, 0.25, 0.5, 1. If set to a value not in this list, it will be treated as 0
Return ValueNone
Usage InstructionsSet the scoring precision according to business needs

setConnti

Function Prototypepublic void setConnti(int connti)
FunctionalityWhether to enable liaison and plosion loss detection, default is 0, applies only to English
Input Parametersconnti: 0 to disable, 1 to enable
Return ValueNone
Usage InstructionsDefaults to 0, can be left unset or set to 0 if this feature is not needed. Setting to 1 enables liaison and plosion loss detection

setServerAPI

Function Prototypepublic void setServerAPI(String serverAPI)
FunctionalitySet online server address, request specified domain server
Input ParametersserverAPI: Provided domain name
Return ValueNone
Usage InstructionsNeeds to be set before initialization, if not set, the common domain will be used

setTestServerAPI

Function Prototypepublic void setTestServerAPI(String testServerAPI)
FunctionalitySet online test server address, request specified domain server
Input ParameterstestServerAPI: Provided domain name
Return ValueNone
Usage InstructionsNeeds to be set before initialization, if not set, the common domain will be used

setI18n

Function Prototypepublic void setI18n(SpeechEval.I18n i18n)
FunctionalitySet internationalization return language type, returns corresponding prompt information (warnings and errors) based on the set language type
Input Parametersi18n: Language type parameter, supports EN, ZH, None. EN: English, ZH: Chinese, None: SDK will take system language
Return ValueNone
Usage InstructionsNeeds to be set before initialization. If not set or set to None, it will take the system language. If system language is Chinese, returns Chinese prompt information, otherwise returns English prompt information

init

Function Prototypepublic ErrorCodes.ErrorCode init(String appId, String appSecret, String userId)
FunctionalityInitialize service
Input ParametersuserId: User identity for statistical information
Return ValueError code object, containing error code and error message
Usage InstructionsInitialize service

setParamsJson

Function Prototypepublic void setParamsJson(JSONObject json)
FunctionalitySet parameter object
Input ParametersNone
Return ValueJSON object
Usage InstructionsUsed to set JSON parameters

setClientData

Function Prototypepublic void setClientData(String clientData)
FunctionalitySet custom parameters, customers can pass in their required parameters, which will be returned in the response as the clientData field
Input ParametersNone
Return ValueNone
Usage InstructionsUsed to set custom request parameters, only supports string type. If passing other types, it's recommended to convert to string type

setEnableWS

Function Prototypepublic void setEnableWS(String isEnableWS)
FunctionalitySet whether to enable WS server, defaults to WSS
Input ParametersisEnableWS: Default is false
Return ValueNone
Usage InstructionsisEnableWS by default is false, can be left unset. If HTTP and WS support is needed, set isEnableWS to true

createRecorder

Function Prototypepublic Recorder createRecorder()
FunctionalityGet Recorder object
Input ParametersNone
Return ValueRecorder object
Usage InstructionsWhen using SDK for recording, get the Recorder object and pass it to the start() method

start

Function Prototypepublic ErrorCodes.ErrorCode start(Recorder recorder)
FunctionalityStart evaluation (using SDK for recording)
Input Parametersrecorder: Recorder object obtained from createRecorder()
Return ValueError code object
Usage InstructionsStart evaluation (using SDK for recording)
Function Prototypepublic ErrorCodes.ErrorCode start(String wavPath)
FunctionalityStart evaluation (send audio file)
Input ParameterswavPath: Audio file path
Return ValueError code object
Usage InstructionsStart evaluation (send audio file), automatically sends the audio, completes evaluation upon sending completion
Function Prototypepublic ErrorCodes.ErrorCode start()
FunctionalityStart evaluation (manual audio packet sending)
Input ParametersNone
Return ValueError code object
Usage InstructionsStart evaluation (manual audio packet sending), need to call feed() method later to send audio data packets

feed

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

stop

Function Prototypepublic void stop()
FunctionalityStop evaluation
Input ParametersNone
Return ValueNone
Usage InstructionsStop evaluation

cancel

Function Prototypepublic void cancel()
FunctionalityCancel evaluation after starting
Input ParametersNone
Return ValueNone
Usage InstructionsCancel evaluation after starting, no evaluation results returned

destroy

Function Prototypepublic void destroy()
FunctionalityRelease evaluation resources
Input ParametersNone
Return ValueNone
Usage InstructionsGenerally, this can be called in Activity.onDestroy

update

Function Prototypepublic void update(true, OnUpdateListener listener)
FunctionalityManually generate new token
Input Parameterslistener: Callback for update completion
Return ValueNone
Usage InstructionsGenerally, no need for manual calling

getExpireTimestamp

Function Prototypepublic long getExpireTimestamp(true)
FunctionalityQuery token expiration time
Input ParametersFixed to true
Return ValueUNIX timestamp
Usage InstructionsToken validity period is 168 hours

SpeechEval.LangType Class

Language types for speech evaluation

MemberMeaning
enUSEnglish

SpeechEval.Mode Class

Evaluation topics

MemberMeaning
WORDWord type
SENTENCESentence type
CHAPTERParagraph type
PHONEMEPhoneme type
QAQuestion and Answer type
TOPICPicture description/Essay type
RETELLRetelling type
RECITERecitation type
WORDCHECKWord correction type
SENTENCECHECKSentence correction type
EXTCHOICEExtended choice type

SpeechEval.Listener Class

Callback interface for speech evaluation

onResult

Function Prototypevoid onResult(String result)
FunctionalityCallback method for evaluation results
Callback Return Valuesresult: Evaluation result
Return ValueNone
Usage InstructionsCallback method for evaluation results

onStartRecording

Function Prototypevoid onStartRecording(String taskId)
FunctionalityCallback method when recording starts
Callback Return ValuesNone
Return ValueNone
Usage InstructionsCallback method when recording starts

onStopSending

Function Prototypevoid onStopSending()
FunctionalityCallback method when evaluation ends
Callback Return ValuesNone
Return ValueNone
Usage InstructionsCallback method when evaluation ends

onGetAudio

Function Prototypevoid onGetAudio(byte[] data)
FunctionalityReal-time return of audio when using recording mode for evaluation
Callback Return Valuesdata: Audio data
Return ValueNone
Usage InstructionsReal-time audio data is returned when using recording mode for evaluation

onGetVolume

Function Prototypevoid onGetVolume(double volume)
FunctionalityReal-time return of volume when using recording mode for evaluation
Callback Return Valuesvolume: Volume level
Return ValueNone
Usage InstructionsReal-time volume level is returned when using recording mode for evaluation

onError

Function Prototypevoid onError(String taskId, String code, String msg)
FunctionalityCallback for errors during evaluation
Callback Return Valuescode: Error code
msg: Error message
Return ValueNone
Usage InstructionsCallback for errors during evaluation, no result in onResult

onWarning

Function Prototypevoid onWarning(String taskId, String code, String msg)
FunctionalityCallback for warnings during evaluation
Callback Return Valuescode: Error code
msg: Error message
Return ValueNone
Usage InstructionsCallback for warnings during evaluation, 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.