Skip to main content
Paraformer-Realtime

Paraformer real-time speech recognition iOS SDK

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

Paraformer models are available only in the China North 2 (Beijing) region. Use an API key created in that region. See Regions and endpoints.
User guide: For an introduction to the models and model selection recommendations, see Real-time speech recognition - Fun-ASR/Gummy/Paraformer.

Getting started

  1. Obtain an API key: Obtain an API key
To grant temporary access permissions to third-party applications or users, or want to strictly control risky operations such as accessing or deleting sensitive data, use a temporary API key. A temporary API key is valid for 60 seconds and must be obtained again after it expires.
  1. Download the SDK and run the sample code:
    • 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.
    • 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:
The following uses the China North 2 (Beijing) endpoint. Paraformer is available only in this region. API keys are region-specific. See Regions and endpoints.
{
    "url": "wss://cn-beijing.maas.qwencloudapi.com/api-ws/v1/inference",
    "apikey": "st-****",
    "device_id": "my_device_id",
    "service_mode": "1"
}
  • Parameter descriptions
ParameterTypeRequiredDescription
urlStringYesThe service endpoint. The value is fixed to wss://cn-beijing.maas.qwencloudapi.com/api-ws/v1/inference.
apikeyStringYesAPI key. For better security, use a short-lived temporary API key to reduce the risk of leaking a long-term key.
service_modeStringYesExecution mode. For real-time speech recognition, the value must be "1".
device_idStringYesA 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_pathStringNoThe 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_wavStringNoSpecifies 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_sizeintNoSets 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_levelintNoControls 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_typeintYesThe type of the Voice Service. The value for real-time speech recognition is fixed to 4.
nls_configobjectYesThe core configuration object for speech recognition. It contains key parameters such as model selection and recognition effect control.
nls_config.modelstringYesSpeech recognition model.
nls_config.sr_formatstringYesThe format of the audio to be recognized. Supported audio formats: pcm, wav, opus. Tip: - 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_rateintYesThe 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_enabledbooleanNoSpecifies whether to filter out filler words, such as "um" and "ah". Default value: false.
nls_config.language_hintsarray[string]NoSets 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_enabledbooleanNoSets 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_silenceintNoThe 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_enabledbooleanNoSpecifies 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_enabledbooleanNoSpecifies 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.heartbeatbooleanNoSpecifies 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_enabledbooleanNoSpecifies 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_idstringNoThe 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.

Key interfaces

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
ParameterTypeDescription
parameterschar*A JSON string that contains authentication, connection, and debugging parameters. For more information, see Connection and control parameters.
levelNuiSdkLogLevelControls the logging level of the SDK itself.
save_logBOOLSpecifies 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;
  • Parameter descriptions
ParameterTypeDescription
paramschar*Speech recognition effect parameters.
  • Return value

nui_dialog_start

Starts recognition.
  • Method signature
-(NuiResultCode) nui_dialog_start:(NuiVadMode)vad_mode
                      dialogParam:(const char *)dialog_params;
  • Parameter descriptions
ParameterTypeDescription
vad_modeNuiVadModeVAD mode. This is fixed at MODE_P2T.
dialog_paramschar*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: See Example 1 below
Example 1 (Description):
{
  "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
ParameterTypeDescription
forceBOOLSpecifies 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
ParameterTypeDescription
nuiEventNuiCallbackEventCallback event.
dialoglongSession code. You can ignore this parameter.
wuwchar*Wake word feature. You can ignore this parameter.
asr_resultchar*Speech recognition result.
finishBOOLA flag that indicates whether the current recognition round has ended.
codeintValid 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
ParameterDescription
STATE_OPENThe interaction has started. You can open the recording device to start recording.
STATE_PAUSEThe interaction has stopped. You can stop recording.
STATE_CLOSEThe 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
ParameterTypeDescription
audioDatachar *The audio data to fill.
lenintThe 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

EventDescription
EVENT_TRANSCRIBER_STARTEDThe task has started successfully.
EVENT_VAD_STARTThis event is triggered as soon as the task starts. It does not indicate that the start of human speech has been detected.
EVENT_VAD_ENDThe end of human speech has been detected.
EVENT_ASR_PARTIAL_RESULTIntermediate speech recognition result.
EVENT_ASR_ERRORAn error occurred during speech recognition.
EVENT_MIC_ERRORTriggered because no audio data was received for two consecutive seconds.
EVENT_SENTENCE_ENDThe end of a sentence has been detected. A complete recognition result for one sentence is returned at this time.
EVENT_TRANSCRIBER_COMPLETESpeech recognition has ended.
Paraformer real-time speech recognition iOS SDK - QwenCloud