# iOS SDK

> Integrate the DolphinSOE pronunciation assessment SDK into an iOS app with SDKParams.h, SpeechEvaluation.h and EvalListener.h.

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

## 1. Integration Steps

### 1.1. SDK Overview

1. The **DolphinAI Speech Evaluation SDK** consists of three main components: `SDKParams.h`, `SpeechEvaluation.h`, and `EvalListener.h`.
2. `SDKParams.h` is used to configure the parameters required to initialize the engine object and start the evaluation.
3. `SpeechEvaluation.h` is used to manage the engine object.
4. `EvalListener.h` handles callbacks from the engine.
5. The **DolphinAI Speech Evaluation SDK** supports evaluating audio in **WAV** or **PCM** formats only.

### 1.2. SDK Import

1.1 **Dynamic Library (Manual Import)**: Drag `SpeechEvaluate.framework` into the project. Then, under `General -> Frameworks, Libraries, and Embedded Content`, change the `Embed` setting for `SpeechEvaluate.framework` to `Embed & Sign`.

1.2 **Static Library (Manual Import)**: Simply drag `SpeechEvaluate.framework` into the project.

2. Add `Privacy - Microphone Usage Description` to the project's `info.plist` file to grant microphone access permissions.

3. Ensure that the `pod` file includes `SocketRocket` version 0.6.0 and `SSZipArchive` version 2.4.0.

### 1.3. SDK Implementation

1. **Import Header File**
   ```objective-c
   #import <SpeechEvaluate/SpeechEvaluate.h>
   ```

2. **Configure Main Parameters**
   ```objective-c
   // Configure main parameters
   SDKParams *params = [[SDKParams alloc] init];
   params.langType = @"en-US";
   params.sampleRate = 16000; // Sample rate
   params.appId = @"appId";
   params.appSecret = @"appSecret";
   params.responseTimeout = 15;
   params.connectTimeout = 15;
   params.ratio = 1.0; // Scoring adjustment coefficient, range: 0.8-1.5, default value: 1
   ```

3. **Initialize the Engine**
   ```objective-c
   EvaluateLanguage *evaluateLanguage = [[EvaluateLanguage alloc] init];
   evaluateLanguage.english = OralOnline; // Set engine language to English, omit if not required
   evaluateLanguage.japanese = OralOnline; // Set engine language to Japanese, omit if not required
   SpeechEvaluation *_oralOnlineManager = [[SpeechEvaluation alloc] init];
   [_oralOnlineManager setInitSDK:self params:params type:evaluateLanguage];

   // Note: Set the properties of evaluateLanguage as needed. If not set, it defaults to None.
   ```

4. **Follow `EvalListener` Protocol in Files Requiring Evaluation**\
   In files where the evaluation function is needed, make sure to adopt the `EvalListener` protocol.

5. **Start and Stop Evaluation**\
   **Start Evaluation**

   ```objective-c
   // Start Evaluation
   - (void)startEvaluating:(UIButton *)button {
       SDKParams *params = [_speechSDK getInitSDKParams];
       params.mode = @"word"; // Set the mode, e.g., word-based evaluation
       params.refText = @"hello"; // Set reference text
       params.scale = 100; // Set scale
       params.clentData = @"1111"; // Set custom parameters, customer can provide their own parameters.
       
       // Set type parameters; dict_type defaults to IPA88, no need to set if not required.
       // If pronunciation is not specified, no need to set the pronunciation parameter.
       NSDictionary *jsonDict = @{
           @"mode": @"word",
           @"refText": @"market",
           @"dict_type": @"IPA88",
           @"pronunciation": @[@{@"ipa": @YES, @"text": @"market", @"phonemes": @"mɑːrkɪt"}]
       };
       [_oralManager setParamsJson:jsonDict];
       
       // Start recording
       [_speechSDK startRecording];
   }
   ```

   **Stop Evaluation**

   ```objective-c
   // Stop Evaluation
   - (void)stopEvaluating:(UIButton *)button {
       // Stop recording and return result
       [_speechSDK stopRecording];
   }
   ```

## Class Introduction

### SDKParams

1. **Set appId**

\- **@property** NSString \*appId;

| **Parameter** | **Description** |
| :- | :- |
| appId | appId |

2. **Set appSecret**

\- **@property** NSString \*appSecret;

| **Parameter** | **Description** |
| :- | :- |
| appSecret | appSecret |

3. **Set Evaluation Mode**

\- **@property** NSString \*mode;

| **Parameter** | **Description** |
| :- | :- |
| mode | Word: word, Sentence: sentence, Passage: chapter, Q\&A: qa, Retelling: retll, Picture Description: topic |

4. **Set Evaluation Text**

\- **@property** NSString \*refText;

| **Parameter** | **Description** |
| :- | :- |
| refText | Evaluation text |

5. **Set Audio Sampling Rate**

\- **@property** **int** sampleRate;

| **Parameter** | **Description** |
| :- | :- |
| sampleRate | Audio sampling rate (Hz), currently only supports 16000 |

6. **Set Evaluation Language Type**

\- **@property** NSString \*langType;

| **Parameter** | **Description** |
| :- | :- |
| langType | Evaluation language: `en-US` for English or `ja-JP` for Japanese |

7. **Set Evaluation Scale**

\- **@property** **int** scale;

| **Parameter** | **Description** |
| :- | :- |
| scale | Evaluation scale, range: 1-100 |

8. **Set Response Timeout (Seconds)**

\- **@property** **int** responseTimeout;

| **Parameter** | **Description** |
| :- | :- |
| responseTimeout | Range: 5-60, default value 15 |

9. **Set Connection Timeout (Seconds)**

\- **@property** **int** connectTimeout;

| **Parameter** | **Description** |
| :- | :- |
| connectTimeout | Range: 5-60, default value 15 |

10. **Set Evaluation Looseness**

\- **@property** **int** looseness;

| **Parameter** | **Description** |
| :- | :- |
| looseness | Evaluation looseness, range: 0-9, higher value means more lenient scoring |

11. **Set Evaluation Adjustment Coefficient**

\- **@property** **float** ratio;

| **Parameter** | **Description** |
| :- | :- |
| ratio | Evaluation adjustment coefficient, range: 0.8-1.5, default value 1.0 |

12. **Set Real-Time Full Response**

\- **@property** **bool** realtime\_full;

| **Parameter** | **Description** |
| :- | :- |
| realtime\_full | Controls whether to return full content |

13. **Enable Comparison Feature**

\- **@property** **NSString** comparison;

| **Parameter** | **Description** |
| :- | :- |
| comparison | Enables comparison feature when provided |

14. **Enable Fluency Field in Dictionary**

\- **@property** **bool** enable\_fluency\_dict;

| **Parameter** | **Description** |
| :- | :- |
| enable\_fluency\_dict | Whether to return the fluency field in dictionary type, only supports chapter and recite |

15. **Enable English Evaluation for Linking and Voicing Loss Detection**

\- **@property** **int** connti;

| **Parameter** | **Description** |
| :- | :- |
| connti | Default is 0. If set to 1, linking and voicing loss detection will be enabled |

16. **Set Maximum Prefix Silence in Milliseconds**

\- **@property** **int** maxPrefixSilenceMs;

| **Parameter** | **Description** |
| :- | :- |
| maxPrefixSilenceMs | Controls the maximum duration of silence before the audio starts in milliseconds, range: 0-30000 |

17. **Set Maximum Suffix Silence in Milliseconds**

\- **@property** **int** maxSuffixSilenceMs;

| **Parameter** | **Description** |
| :- | :- |
| maxSuffixSilenceMs | Controls the maximum duration of silence after the audio ends in milliseconds, range: 0-30000, will trigger a warning and stop the evaluation |

18. **Set Scoring Precision**

\- **@property** **NSString** precision;

| **Parameter** | **Description** |
| :- | :- |
| precision | Scoring precision, default is 0. Only supports values: 0, 0.1, 0.25, 0.5, 1 |

19. **Set User Identifier**

\- **@property** **NSString** userId;

| **Parameter** | **Description** |
| :- | :- |
| userId | Identifies different users |

20. **Set Custom Parameters**

\- **@property** **NSString** clientData;

| **Parameter** | **Description** |
| :- | :- |
| clientData | Allows the user to pass custom parameters, which will be returned in the response as the clientData field. Only supports string type; for other types, convert them into a string before passing. |

21. **Set Whether to Use AVAudioSession Externally**

\- **@property** **bool** initiativeSetAudio;

| **Parameter** | **Description** |
| :- | :- |
| initiativeSetAudio | Whether the SDK sets AVAudioSession externally |

### SpeechEvaluation

1. **Initialize the Evaluation SDK**

   - (**void**) `initSDK`: (**id**\<EvalListener>)listener params:(SDKParams \*)params type:(OralEvaluatingType)type;

   | **Parameter Name** | **Description** |
   | :- | :- |
   | listener | Evaluation listener |
   | params | Parameters required to initialize the SDK |
   | type | Online: OralOnLine |

2. **Start Recording**
   - (**void**) `startRecording`;

3. **Stop Recording**
   - (**void**) `stopRecording`;

4. **Cancel Recording**
   - (**void**) `cancleRecording`;

5. **Evaluate Using Local File**

   - (**void**) `startEvaluateOralWithWavPath:(NSString *)wavPath`;

   | **Parameter Name** | **Description** |
   | :- | :- |
   | wavPath | Full path of the wav audio file |

6. **Initialize Model Codec**

   - (**void**) `doStart:(FinishBlock)finishBlock`;

   | **Parameter Name** | **Description** |
   | :- | :- |
   | finishBlock | Indicates whether the codec was initialized successfully |

7. **Set Data for Evaluation Engine**

   - (**void**) `doSetData:(NSData *)data isLast:(bool)isLast`;

   | **Parameter Name** | **Description** |
   | :- | :- |
   | data | Audio data |
   | isLast | Whether this is the last audio data packet |

8. **Stop Evaluation and Return Result**
   - (**void**) `doStop`;

9. **Cancel Audio Data Transmission**
   - (**void**) `cancelSetData`;

10. **Get Initialized SDK Parameters**

- (**SDKParams**) `getInitSDKParams`;

11. **Whether to Save Recorded Audio**

- (**void**) `setSaveAudio:(bool)save`;

| **Parameter Name** | **Description** |
| :- | :- |
| save | Default is YES. Set to YES to save the audio, NO to not save the audio. |

12. **Set Audio Save Path**

- (**void**) `setAudioSavePath:(NSString*)wavePath`;

| **Parameter Name** | **Description** |
| :- | :- |
| wavePath | Path to save the audio file (it is recommended to create a folder and provide the folder path) |

> 1. If `setSaveAudio(true)` is set but `setAudioSavePath` is not, the SDK will save to the default path and notify the saved path via `onSaveAudioFile(NSString *)path`.
> 2. The SDK will delete audio files older than 7 days.

13. **Manually Release Online Evaluation Connection**

- (**void**) `releaseConnect`;

> If no manual disconnection is needed, this can be left unset.

14. **Set Evaluation Domain Name (must be set before initialization)**

- (**void**) `setServiceAPI:(NSString *)serviceAPI`;

| **Parameter Name** | **Description** |
| :- | :- |
| serviceAPI | Set the server address for online requests. Must be set before initialization. If not set, the default domain will be used. |

15. **Set Internationalization Language Type (must be set before initialization, default is Chinese)**

- (**void**) `setI18nType:(EvaluateI18nType)i18n`;

| **Parameter Name** | **Description** |
| :- | :- |
| i18n | Supports enums `zh` (Chinese) and `en` (English). After setting, prompt messages will return in the specified language. If not set, the default will be Chinese. |

16. **Set Additional Parameters**

- (**void**) `setParamsJson:(NSDictionary *)ParamsDic`;

| **Parameter Name** | **Description** |
| :- | :- |
| ParamsDic | Allows setting parameters for question types, e.g., `{ @"mode": @"word", @"refText": @"market", @"dict_type": @"IPA88", @"pronunciation":@[@{@"ipa":@YES,@"text":@"market",@"phonemes":@"mɑːrkɪt"}] }` |

### EvalListener

1. **Return Evaluation Result**

   - (**void**) `onResult: (NSString *)result WithOnline:(BOOL)online;`

   | **Parameter Name** | **Description** |
   | :- | :- |
   | result | Evaluation result |
   | online | `true` for online evaluation, `false` for offline evaluation |

2. **Callback Method After WebSocket Connection Success**

   - (**void**) `onwsStart:(NSString *)taskId;`

   | **Parameter Name** | **Description** |
   | :- | :- |
   | taskId | Task ID returned from the evaluation, globally unique, corresponds to the audio file |

3. **Indicates Successful Start of Recording (Called when recording starts)**
   - (**void**) `onStartRecording;`

4. **Return Real-Time Recorded Audio Data (PCM format)**

   - (**void**) `onGetAudio:(NSData *)data;`

   | **Parameter Name** | **Description** |
   | :- | :- |
   | data | Audio data |

5. **Return Volume**

   - (**void**) `onGetVolume:(double)volume;`

   | **Parameter Name** | **Description** |
   | :- | :- |
   | volume | Volume level |

6. **Return Path of Saved Audio File**

   - (**void**) `onSaveAudioFile:(NSString *)path;`

   | **Parameter Name** | **Description** |
   | :- | :- |
   | path | Path where the audio is saved |

7. **Error Callback (Returns Error Code, Error Message, and Task ID)**

   - (**void**) `onError:(NSString *)code msg:(NSString *)msg taskId:(nullable NSString *)taskId;`

   | **Parameter Name** | **Description** |
   | :- | :- |
   | code | Error code |
   | msg | Error message |
   | taskId | Task ID |

8. **Warning Callback (Returns Warning Code, Warning Message, and Task ID)**

   - (**void**) `onWarning:(NSString *)code msg:(NSString *)msg taskId:(nullable NSString *)taskId;`

   | **Parameter Name** | **Description** |
   | :- | :- |
   | code | Warning code |
   | msg | Warning message |
   | taskId | Task ID |

## Response Results

Refer to the corresponding question type's [interface parameters](https://soe.dolphinvoice.ai/en/docs/mode/intro) documentation.

## Status Code Table

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

## Frequently Asked Questions

1. **What is the minimum iOS version supported by the SDK?**

   The iOS version of the SDK supports iOS 10 and above.

2. **Which platforms does the voice evaluation support?**

   The voice evaluation currently supports: Android, iOS, Web, Mini Program, Linux, Windows, Dictionary Pen, RTOS, and other application platforms.

3. **What audio formats does the voice evaluation support?**

   For information on audio formats, please refer to the [Supported Audio Formats](https://soe.dolphinvoice.ai/en/docs/public/datadict/format) document.

4. **What are the error codes and their solutions?**

   For an introduction to error codes, please check the [Status Code](https://soe.dolphinvoice.ai/en/docs/sdk/status) document.

5. **What question types, texts, audio duration limits, results, and meanings of each field does the voice evaluation support?**

   For supported question types, text, and audio duration limits, please refer to the [Question Types](https://soe.dolphinvoice.ai/en/docs/mode/intro) document and the [Parameter Introduction](https://soe.dolphinvoice.ai/en/docs/mode/common) document.

6. **Why is the audioUrl field missing or blank in the result?**

   If it is an online evaluation, you need to pass `audioUrl=true` before the evaluation for the results to return an audio URL. For offline evaluation, whether `audioUrl=true` or `false`, no audio URL will be returned.

7. **How long is the evaluation audio address stored?**

   The evaluation audio address is stored by default for **30 days**. If longer storage is needed, it is recommended to download it to your server.