Paraformer iOS SDK

Updated at:

This document provides a detailed guide on how to use the Paraformer real-time speech recognition iOS SDK to convert speech to text.

ImportantAlibaba Cloud Model Studio has released a workspace-specific domain for the China (Beijing) region. The new dedicated domain delivers superior performance and higher stability for inference requests. We recommend migrating from dashscope.aliyuncs.com to {WorkspaceId}.cn-beijing.maas.aliyuncs.com.

Replace {WorkspaceId} with your actual Workspace ID. The existing domain remains fully functional.

User guide: For an introduction to the models and model selection recommendations, see Real-time speech recognition - Fun-ASR/Gummy/Paraformer.

Prerequisites

  1. Obtain and configure an API key. Do not hardcode a long-lived API key in a mobile app. We recommend generating a temporary API key on your application server and sending it to the client.

Install the SDK

  • Download the latest SDK package.
  • Unzip the package and add nuisdk.framework to your project.
  • In the Build Phases settings, under Link Binary With Libraries, add nuisdk.framework.
  • In the General settings, under Frameworks, Libraries, and Embedded Content, set nuisdk.framework to Embed & Sign.

Quick start

Open the sample project in Xcode. The sample code is in the DashParaformerSpeechTranscriberViewController class. Replace the API key to test the feature.

Call procedure

  1. Initialize the SDK.
  2. Configure the parameters as needed. Use the nui_initialize interface to set connection and control parameters. Use the nui_set_param interface to set speech recognition effect parameters.
  3. Call nui_dialog_start to start the recognition process.
  4. In the onNuiAudioStateChanged callback, start the recording device based on the audio state.
  5. In the onNuiNeedAudioData callback, continuously provide the recorded audio data.
  6. In the onNuiEventCallback callback, listen for events and retrieve the speech recognition results.
  7. Call nui_dialog_cancel to stop the recognition. Confirm that the recognition has ended by listening for the EVENT_TRANSCRIBER_COMPLETE event.
  8. When you no longer need the recognition feature, call the nui_release interface to release the SDK resources.

Request parameters

Connection and control parameters

Configure these parameters by passing a JSON string to the parameters parameter of the nui_initialize interface.

  • Parameter example: The following code provides an example of the JSON string. Not all parameters are listed. You can add parameters as needed during encoding:
{
    "url": "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference",
    "apikey": "st-****",
    "device_id": "my_device_id",
    "service_mode": "1"
}
  • Parameter descriptions

    Parameter

    Type

    Required

    Description

    url

    String

    Yes

    The service endpoint. The value is fixed to wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference. Replace {WorkspaceId} with your actual workspace ID.

    apikey

    String

    Yes

    API key. For better security, use a short-lived temporary API key to reduce the risk of leaking a long-term key.

    service_mode

    String

    Yes

    Execution mode. For real-time speech recognition, the value must be "1".

    device_id

    String

    Yes

    A unique string that identifies the end user. You can set this to the user ID within your application or a unique device identifier generated by the client. This ID is mainly used for log tracking and troubleshooting.

    debug_path

    String

    No

    The storage path for log files.

    This parameter takes effect only when you call the nui_initialize API and set save_log to YES. In this case, you must set the log file path. Otherwise, an error occurs.

    A maximum of two log files are kept locally.

    save_wav

    String

    No

    Specifies whether to save audio files for debugging. The audio files are saved to debug_path.

    Default value: "false".

    Valid values:

    • "true": Yes

    • "false": No

    This parameter takes effect only when you set save_log to true when calling the nui_initialize API. Additionally, debug_path must also be set.

    max_log_file_size

    int

    No

    Sets the maximum size of a log file in bytes.

    This parameter takes effect only when you call the nui_initialize interface with save_log set to YES.

    Default value: 104857600 (100 × 1024 × 1024 bytes, or 100 MiB).

    log_track_level

    int

    No

    Controls the filtering level for log content sent externally through the log callback (onNuiLogTrackCallback).

    Default value: 2.

    Valid values:

    • 0: LOG_LEVEL_VERBOSE

    • 1: LOG_LEVEL_DEBUG

    • 2: LOG_LEVEL_INFO

    • 3: LOG_LEVEL_WARNING

    • 4: LOG_LEVEL_ERROR

    • 5: LOG_LEVEL_NONE (disables this feature)

    Note: log_track_level and level (set using the nui_initialize API) determine which logs are sent to the callback. A log message is sent to the callback only if its level value is greater than or equal to the values of both log_track_level and level. For example, if log_track_level is set to 2 (INFO) and level is set to 3 (WARNING), only logs at the WARNING level or higher (numeric value >=3) are sent to the callback.

Speech recognition effect parameters

Configure these parameters by passing a JSON string to the params parameter of the nui_set_param interface.

  • Parameter example: The following code provides an example of the JSON string. Not all parameters are listed. You can add parameters as needed during encoding:
{
    "service_type": 4,
    "nls_config": {
        "model": "paraformer-realtime-v2",
        "sr_format": "pcm",
        "sample_rate": "16000"
    }
}
  • Parameter descriptions
    Top-level parameterTypeRequiredDescription

    service_type

    int

    Yes

    The type of the Voice Service. The value for real-time speech recognition is fixed to 4.

    nls_config

    object

    Yes

    The core configuration object for speech recognition. It contains key parameters such as model selection and recognition effect control.

    nls_config.model

    string

    Yes

    Speech recognition model.

    nls_config.sr_format

    string

    Yes

    The format of the audio to be recognized.

    Supported audio formats: pcm, wav, opus.

    Important

    • opus: Must be PCM encoded. The software development kit (SDK) internally encodes it into the OPUS format.
    • wav/pcm: Must be PCM encoded.

    nls_config.sample_rate

    int

    Yes

    The sample rate of the audio to be recognized, in Hz.

    This varies by model:

    • paraformer-realtime-v2 supports any sample rate.

    • paraformer-realtime-8k-v2 supports only 8000 Hz.

    nls_config.disfluency_removal_enabled

    boolean

    No

    Specifies whether to filter out filler words, such as "um" and "ah".

    Default value: false.

    nls_config.language_hints

    array[string]

    No

    Sets the language codes for the audio to be recognized. If you cannot determine the language in advance, you can leave this parameter unset. The model will automatically detect the language.

    Supported language codes:

    • zh: Chinese
    • en: English
    • ja: Japanese
    • yue: Cantonese
    • ko: Korean
    • de: German
    • fr: French
    • ru: Russian

    This parameter is effective only for models that support multiple languages.

    nls_config.semantic_punctuation_enabled

    boolean

    No

    Sets the sentence segmentation mode.

    Default value: false.

    Valid values:

    • true: Enables semantic segmentation and disables VAD segmentation.
    • false: Enables VAD segmentation and disables semantic segmentation.

    Semantic segmentation provides higher accuracy and is suitable for transcription scenarios such as meetings. Voice Activity Detection (VAD) segmentation has lower latency and is suitable for real-time interactive scenarios.

    This parameter is effective only for v2 and later models.

    nls_config.max_sentence_silence

    int

    No

    The silence duration threshold for Voice Activity Detection (VAD) segmentation, in ms.

    Default value: 800.

    Value range: [200, 6000].

    When the silence duration after a speech segment exceeds this threshold, the system determines that the sentence has ended.

    This parameter is effective only when the semantic_punctuation_enabled parameter is set to false and for v2 and later models.

    nls_config.multi_threshold_mode_enabled

    boolean

    No

    Specifies whether to enable the anti-over-segmentation mode. Enabling this mode prevents VAD from creating excessively long segments.

    Default value: false (disabled).

    Valid values:

    • true: Enabled
    • false: Disabled

    This parameter is effective only when the semantic_punctuation_enabled parameter is set to false and for v2 and later models.

    nls_config.punctuation_prediction_enabled

    boolean

    No

    Specifies whether to automatically add punctuation to the recognition result.

    Default value: true (yes).

    Valid values:

    • true: Yes
    • false: No

    This parameter is effective only for v2 and later models.

    nls_config.heartbeat

    boolean

    No

    Specifies whether to maintain a persistent connection with the server.

    Default value: false.

    Valid values:

    • true: The connection with the server can be maintained without interruption by continuously sending silent audio.
    • false: Even when silent audio is continuously sent, the connection times out and closes after a period of time. This timeout is the default server-side behavior and cannot be configured by the client.

    This parameter is effective only for v2 and later models.

    nls_config.inverse_text_normalization_enabled

    boolean

    No

    Specifies whether to enable Inverse Text Normalization (ITN). When enabled, Chinese numbers are converted to Arabic numerals.

    Default value: true (enabled).

    Valid values:

    • true: Enabled
    • false: Disabled

    This parameter is effective only for v2 and later models.

    nls_config.vocabulary_id

    string

    No

    The ID of the hotword vocabulary, used to improve the recognition accuracy of specific words. This parameter applies to v2 and later models. For information about how to use hotwords, see Customize hotwords.

API reference

NeoNui

nui_initialize

Initializes the speech recognition SDK instance. The SDK uses the singleton pattern. Do not initialize the instance again before you call nui_release.

  • Method signature
-(NuiResultCode) nui_initialize:(const char *)parameters
                       logLevel:(NuiSdkLogLevel)level
                        saveLog:(BOOL)save_log;
  • Parameter descriptions

    Parameter

    Type

    Description

    parameters

    char*

    A JSON string that contains authentication, connection, and debugging parameters. For more information, see Connection and control parameters.

    level

    NuiSdkLogLevel

    Controls the logging level of the SDK itself.

    save_log

    BOOL

    Specifies whether to save binary logs. If this parameter is set to YES, you must specify a path using debug_path in Connection and control parameters, and you can set the file size using max_log_file_size.

  • Return value

nui_set_param

Sets the speech recognition parameters in JSON format. You must call this interface before you call nui_dialog_start.

  • Method signature
-(NuiResultCode) nui_set_params:(const char *)params;

nui_dialog_start

Starts recognition.

  • Method signature
-(NuiResultCode) nui_dialog_start:(NuiVadMode)vad_mode
                      dialogParam:(const char *)dialog_params;
  • Parameter descriptions
    ParameterTypeDescription

    vad_mode

    NuiVadMode

    VAD mode. This is fixed at MODE_P2T.

    dialog_params

    char*

    When the temporary API key for the apikey parameter in the connection and control parameters expires, you can update it here.

    The content is in JSON format:

    {
      "apikey": "st-****"
    }
    
  • Return value

nui_dialog_cancel

Ends recognition or immediately cancels the current interaction.

  • Method signature
-(NuiResultCode) nui_dialog_cancel:(BOOL)force;
  • Parameter descriptions

    Parameter

    Type

    Description

    force

    BOOL

    Specifies whether to force the task to end without waiting for the final result.

    • YES: Terminates the task immediately without waiting for the server-side to return the final recognition result.

    • NO: Ends the task, but waits for the complete result to be returned.

  • Return value

nui_release

Releases all internal SDK resources and forcefully terminates all ongoing tasks. After this method is called, the SDK instance becomes unavailable. To use the instance again, you must call nui_initialize to re-initialize it.

  • Method signature
-(NuiResultCode) nui_release;
  • Return value

nui_get_version

Retrieves the current SDK version information.

  • Method signature
-(const char*) nui_get_version;
  • Return value

    The current version of the SDK.

nui_get_all_response

Retrieves the complete information of the current event callback.

  • Method signature
-(const char*) nui_get_all_response;
  • Return value

    A JSON string that contains the complete event information.

NeoNuiSdkDelegate: Listener callbacks

onNuiEventCallback: Listen for events and speech recognition results

  • Method signature
-(void) onNuiEventCallback:(NuiCallbackEvent)nuiEvent
                    dialog:(long)dialog
                 kwsResult:(const char *)wuw
                 asrResult:(const char *)asr_result
                  ifFinish:(BOOL)finish
                   retCode:(int)code;
  • Parameter descriptions

    Parameter

    Type

    Description

    nuiEvent

    NuiCallbackEvent

    Callback event.

    dialog

    long

    Session code. You can ignore this parameter.

    wuw

    char*

    Wake word feature. You can ignore this parameter.

    asr_result

    char*

    Speech recognition result.

    finish

    BOOL

    A flag that indicates whether the current recognition round has ended.

    code

    int

    Valid only when the EVENT_ASR_ERROR event occurs.

onNuiAudioStateChanged: Listen for audio state

The SDK uses this callback to notify you when to start or stop recording.

  • Method signature
-(void) onNuiAudioStateChanged:(NuiAudioState)state;
  • NuiAudioState descriptions

    Parameter

    Description

    STATE_OPEN

    The interaction has started. You can open the recording device to start recording.

    STATE_PAUSE

    The interaction has stopped. You can stop recording.

    STATE_CLOSE

    The SDK instance has been released. You can completely shut down the recording device.

onNuiNeedAudioData: Fill audio data for recognition

After recognition starts, this callback is triggered continuously. You must provide the audio data to be recognized in this callback.

  • Method signature
-(int) onNuiNeedAudioData:(char *)audioData length:(int)len;
  • Parameter descriptions

    Parameter

    Type

    Description

    audioData

    char *

    The audio data to fill.

    len

    int

    The size of the filled audio data in bytes.

onNuiLogTrackCallback: Listen for tracking logs

This callback is used to receive detailed internal logs from the SDK for troubleshooting and debugging.

-(void) onNuiLogTrackCallback:(NuiSdkLogLevel)level
                   logMessage:(const char *)log;

NuiCallbackEvent: Event types

Event

Description

EVENT_TRANSCRIBER_STARTED

The task has started successfully.

EVENT_VAD_START

This event is triggered as soon as the task starts. It does not indicate that the start of human speech has been detected.

EVENT_VAD_END

The end of human speech has been detected.

EVENT_ASR_PARTIAL_RESULT

Intermediate speech recognition result.

EVENT_ASR_ERROR

An error occurred during speech recognition.

EVENT_MIC_ERROR

Triggered because no audio data was received for two consecutive seconds.

EVENT_SENTENCE_END

The end of a sentence has been detected. A complete recognition result for one sentence is returned at this time.

EVENT_TRANSCRIBER_COMPLETE

Speech recognition has ended.