# Harmony SDK

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

Source: https://soe.dolphinvoice.ai/en/docs/sdk/harmonyos

## 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:

```bash
ohpm install @ohos/crypto-js
```

#### 1.2 Integration via ohpem Repository (Remote Integration)

Command: `ohpm install speech_eval_sdk`

Include the following dependencies:

```bash
ohpm install @ohos/crypto-js
```

### 2. Add Application Related Permissions

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

```json
    "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](https://cdn.dolphinvoice.ai/doc/soe/android.svg)

#### ① Request Permissions

```ts
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

```ts
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](https://soe.dolphinvoice.ai/en/docs/mode/common#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](https://soe.dolphinvoice.ai/en/docs/mode/intro) documentation.

##### Example Code

```ts
/**
 * 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)**

```ts
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)**

```ts
// 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](https://soe.dolphinvoice.ai/en/docs/sdk/harmonyos#-initialize-engine-instance) to handle evaluation results in the listener

#### ⑥ **Release Evaluation Resources**

```ts
eval.destroy();
```

### 4. Obfuscation Mechanism

```java
// If obfuscation is needed, exclude SDK from obfuscation
```

## II. API Documentation

### SpeechEval Class

Main class for speech evaluation

**createInstance**

| Function Prototype | `public static getInstance(context: Context): SpeechEval` |
| - | - |
| Functionality | Create an evaluation class object |
| Input Parameters | `context`: Context object |
| Return Value | None |
| Usage Instructions | Create an evaluation class object |

**setListener**

| Function Prototype | `public setListener(listener: Listener): void` |
| - | - |
| Functionality | Set Listener |
| Input Parameters | `listener`: Listener object |
| Return Value | None |
| Usage Instructions | Set Listener |

**setLangType**

| Function Prototype | `setLangType(langType: LangType)` |
| - | - |
| Functionality | Set language type |
| Input Parameters | `langType`: Language code |
| Return Value | None |
| Usage Instructions | Set language type |

**setScale**

| Function Prototype | `setScale(scale: number)` |
| - | - |
| Functionality | Set scoring scale |
| Input Parameters | `scale`: Scoring scale 1-100 |
| Return Value | None |
| Usage Instructions | Set scoring scale |

**setSampleRate**

| Function Prototype | `public void setSampleRate(int sampleRate)` |
| - | - |
| Functionality | Set sampling rate |
| Input Parameters | `sampleRate`: Sampling rate 16000 |
| Return Value | None |
| Usage Instructions | Set sampling rate |

**setLooseness**

| Function Prototype | `public void setLooseness(int looseness)` |
| - | - |
| Functionality | Set scoring leniency |
| Input Parameters | `looseness`: Scoring leniency 0-9 |
| Return Value | None |
| Usage Instructions | Set scoring leniency |

**setConnectTimeout**

| Function Prototype | `public void setConnectTimeout(int timeout)` |
| - | - |
| Functionality | Set connection timeout |
| Input Parameters | `timeout`: Timeout in seconds 1-60 |
| Return Value | None |
| Usage Instructions | Set connection timeout |

**setResponseTimeout**

| Function Prototype | `public void setResponseTimeout(int timeout)` |
| - | - |
| Functionality | Set response timeout |
| Input Parameters | `timeout`: Timeout in seconds 1-60 |
| Return Value | None |
| Usage Instructions | Set response timeout |

**setRatio**

| Function Prototype | `public void setRatio(float ratio)` |
| - | - |
| Functionality | Set score adjustment factor |
| Input Parameters | `ratio`: Score adjustment factor 0.8-1.5 |
| Return Value | None |
| Usage Instructions | This factor adjusts scores between 30-90 (out of 100), other scores remain unchanged<br />`ratio` >1.0 adjusts scores upwards, the closer to 75, the higher the adjustment<br />`ratio` \<1.0 adjusts scores downwards, the closer to 75, the higher the adjustment<br />`ratio` =1.0 does not adjust scores |

**setSaveAudio**

| Function Prototype | `public void setSaveAudio(boolean saveAudio)` |
| - | - |
| Functionality | Set whether to save recording audio |
| Input Parameters | `saveAudio`: true for saving local audio, false for not saving |
| Return Value | None |
| Usage Instructions | Set whether to save recording audio |

**setModelPath**

| Function Prototype | `public void setSaveAudio(String modelPath)` |
| - | - |
| Functionality | Set offline model loading path |
| Input Parameters | `modelPath`: Path to the directory where the model files are stored and unzipped |
| Return Value | None |
| Usage Instructions | Must be an accessible path. Path where the model files are stored and unzipped |

**setMaxPrefixSilenceMs**

| Function Prototype | `public void setMaxPrefixSilenceMs(int maxPrefixSilenceMs)` |
| - | - |
| Functionality | Set the threshold for detecting silence before speech (milliseconds) |
| Input Parameters | `maxPrefixSilenceMs`: Range \[0-30000] |
| Return Value | None |
| Usage Instructions | If 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 Prototype | `public void setMaxSuffixSilenceMs(int maxSuffixSilenceMs)` |
| - | - |
| Functionality | Set the threshold for detecting silence after speech (milliseconds) |
| Input Parameters | `maxSuffixSilenceMs`: Range \[0-30000] |
| Return Value | None |
| Usage Instructions | If 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 Prototype | `public void setPrecision(String precision)` |
| - | - |
| Functionality | Set scoring precision |
| Input Parameters | `precision`: 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 Value | None |
| Usage Instructions | Set the scoring precision according to business needs |

**setConnti**

| Function Prototype | `public void setConnti(int connti)` |
| - | - |
| Functionality | Whether to enable liaison and plosion loss detection, default is 0, applies only to English |
| Input Parameters | `connti`: 0 to disable, 1 to enable |
| Return Value | None |
| Usage Instructions | Defaults 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 Prototype | `public void setServerAPI(String serverAPI)` |
| - | - |
| Functionality | Set online server address, request specified domain server |
| Input Parameters | `serverAPI`: Provided domain name |
| Return Value | None |
| Usage Instructions | Needs to be set before initialization, if not set, the common domain will be used |

**setTestServerAPI**

| Function Prototype | `public void setTestServerAPI(String testServerAPI)` |
| - | - |
| Functionality | Set online test server address, request specified domain server |
| Input Parameters | `testServerAPI`: Provided domain name |
| Return Value | None |
| Usage Instructions | Needs to be set before initialization, if not set, the common domain will be used |

**setI18n**

| Function Prototype | `public void setI18n(SpeechEval.I18n i18n)` |
| - | - |
| Functionality | Set internationalization return language type, returns corresponding prompt information (warnings and errors) based on the set language type |
| Input Parameters | `i18n`: Language type parameter, supports EN, ZH, None. EN: English, ZH: Chinese, None: SDK will take system language |
| Return Value | None |
| Usage Instructions | Needs 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 Prototype | `public ErrorCodes.ErrorCode init(String appId, String appSecret, String userId)` |
| - | - |
| Functionality | Initialize service |
| Input Parameters | `userId`: User identity for statistical information |
| Return Value | Error code object, containing error code and error message |
| Usage Instructions | Initialize service |

**setParamsJson**

| Function Prototype | `public void setParamsJson(JSONObject json)` |
| - | - |
| Functionality | Set parameter object |
| Input Parameters | None |
| Return Value | JSON object |
| Usage Instructions | Used to set JSON parameters |

**setClientData**

| Function Prototype | `public void setClientData(String clientData)` |
| - | - |
| Functionality | Set custom parameters, customers can pass in their required parameters, which will be returned in the response as the clientData field |
| Input Parameters | None |
| Return Value | None |
| Usage Instructions | Used to set custom request parameters, only supports string type. If passing other types, it's recommended to convert to string type |

**setEnableWS**

| Function Prototype | `public void setEnableWS(String isEnableWS)` |
| - | - |
| Functionality | Set whether to enable WS server, defaults to WSS |
| Input Parameters | `isEnableWS`: Default is false |
| Return Value | None |
| Usage Instructions | `isEnableWS` by default is false, can be left unset. If HTTP and WS support is needed, set `isEnableWS` to true |

**createRecorder**

| Function Prototype | `public Recorder createRecorder()` |
| - | - |
| Functionality | Get Recorder object |
| Input Parameters | None |
| Return Value | Recorder object |
| Usage Instructions | When using SDK for recording, get the Recorder object and pass it to the `start()` method |

**start**

| Function Prototype | `public ErrorCodes.ErrorCode start(Recorder recorder)` |
| - | - |
| Functionality | Start evaluation (using SDK for recording) |
| Input Parameters | `recorder`: Recorder object obtained from `createRecorder()` |
| Return Value | Error code object |
| Usage Instructions | Start evaluation (using SDK for recording) |

| Function Prototype | `public ErrorCodes.ErrorCode start(String wavPath)` |
| - | - |
| Functionality | Start evaluation (send audio file) |
| Input Parameters | `wavPath`: Audio file path |
| Return Value | Error code object |
| Usage Instructions | Start evaluation (send audio file), automatically sends the audio, completes evaluation upon sending completion |

| Function Prototype | `public ErrorCodes.ErrorCode start()` |
| - | - |
| Functionality | Start evaluation (manual audio packet sending) |
| Input Parameters | None |
| Return Value | Error code object |
| Usage Instructions | Start evaluation (manual audio packet sending), need to call `feed()` method later to send audio data packets |

**feed**

| Function Prototype | `public void feed(byte[] data)` |
| - | - |
| Functionality | Manually send audio data packets |
| Input Parameters | Audio data, recommended length per send is 1920 bytes |
| Return Value | Error code object |
| Usage Instructions | After calling `start()`, **repeatedly call** `feed()` to pass in audio data |

**stop**

| Function Prototype | `public void stop()` |
| - | - |
| Functionality | Stop evaluation |
| Input Parameters | None |
| Return Value | None |
| Usage Instructions | Stop evaluation |

**cancel**

| Function Prototype | `public void cancel()` |
| - | - |
| Functionality | Cancel evaluation after starting |
| Input Parameters | None |
| Return Value | None |
| Usage Instructions | Cancel evaluation after starting, no evaluation results returned |

**destroy**

| Function Prototype | `public void destroy()` |
| - | - |
| Functionality | Release evaluation resources |
| Input Parameters | None |
| Return Value | None |
| Usage Instructions | Generally, this can be called in `Activity.onDestroy` |

**update**

| Function Prototype | `public void update(true, OnUpdateListener listener)` |
| - | - |
| Functionality | Manually generate new token |
| Input Parameters | `listener`: Callback for update completion |
| Return Value | None |
| Usage Instructions | Generally, no need for manual calling |

**getExpireTimestamp**

| Function Prototype | `public long getExpireTimestamp(true)` |
| - | - |
| Functionality | Query token expiration time |
| Input Parameters | Fixed to true |
| Return Value | UNIX timestamp |
| Usage Instructions | Token validity period is 168 hours |

### SpeechEval.LangType Class

Language types for speech evaluation

| Member | Meaning |
| - | - |
| enUS | English |

### SpeechEval.Mode Class

Evaluation topics

| Member | Meaning |
| - | - |
| WORD | Word type |
| SENTENCE | Sentence type |
| CHAPTER | Paragraph type |
| PHONEME | Phoneme type |
| QA | Question and Answer type |
| TOPIC | Picture description/Essay type |
| RETELL | Retelling type |
| RECITE | Recitation type |
| WORDCHECK | Word correction type |
| SENTENCECHECK | Sentence correction type |
| EXTCHOICE | Extended choice type |

### SpeechEval.Listener Class

Callback interface for speech evaluation

**onResult**

| Function Prototype | `void onResult(String result)` |
| - | - |
| Functionality | Callback method for evaluation results |
| Callback Return Values | `result`: Evaluation result |
| Return Value | None |
| Usage Instructions | Callback method for evaluation results |

**onStartRecording**

| Function Prototype | `void onStartRecording(String taskId)` |
| - | - |
| Functionality | Callback method when recording starts |
| Callback Return Values | None |
| Return Value | None |
| Usage Instructions | Callback method when recording starts |

**onStopSending**

| Function Prototype | `void onStopSending()` |
| - | - |
| Functionality | Callback method when evaluation ends |
| Callback Return Values | None |
| Return Value | None |
| Usage Instructions | Callback method when evaluation ends |

**onGetAudio**

| Function Prototype | `void onGetAudio(byte[] data)` |
| - | - |
| Functionality | Real-time return of audio when using recording mode for evaluation |
| Callback Return Values | `data`: Audio data |
| Return Value | None |
| Usage Instructions | Real-time audio data is returned when using recording mode for evaluation |

**onGetVolume**

| Function Prototype | `void onGetVolume(double volume)` |
| - | - |
| Functionality | Real-time return of volume when using recording mode for evaluation |
| Callback Return Values | `volume`: Volume level |
| Return Value | None |
| Usage Instructions | Real-time volume level is returned when using recording mode for evaluation |

**onError**

| Function Prototype | `void onError(String taskId, String code, String msg)` |
| - | - |
| Functionality | Callback for errors during evaluation |
| Callback Return Values | `code`: Error code<br />`msg`: Error message |
| Return Value | None |
| Usage Instructions | Callback for errors during evaluation, no result in `onResult` |

**onWarning**

| Function Prototype | `void onWarning(String taskId, String code, String msg)` |
| - | - |
| Functionality | Callback for warnings during evaluation |
| Callback Return Values | `code`: Error code<br />`msg`: Error message |
| Return Value | None |
| Usage Instructions | Callback for warnings during evaluation, result in `onResult` |

## III. Response Results

Please refer to the corresponding question type's [Interface Parameters](https://soe.dolphinvoice.ai/en/docs/mode/intro) documentation.

## IV. Status Code Table

Please refer to the [Status Code](https://soe.dolphinvoice.ai/en/docs/sdk/status) documentation.