Qwen-Audio-Realtime iOS SDK

Updated at:

Use Qwen-Audio-Realtime real-time voice dialogue iOS SDK to enable real-time audio input and speech or text output.

For connection and authentication, see WebSocket access. For event fields and JSON examples, see Client events and Server events.

User guide: For the model introduction and selection advice, see Real-time voice conversation.

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.
  • Extract the ZIP package and add the nuisdk.xcframework in it to the project.
  • In Build Phases → Link Binary With Libraries, add nuisdk.xcframework.
  • In General → Frameworks, Libraries, and Embedded Content, set nuisdk.xcframework to Embed & Sign.

Quick start

Open the sample project in Xcode. The sample code is located in DashQwenAudioChatViewController.m. Replace the API Key to try the feature.

Call procedure

  1. Initialize the SDK
  2. Set parameters based on your business needs: use the nui_initialize method to set the connection and control parameters; use the nui_set_params method to set the voice conversation parameters.
  3. Call nui_dialog_start to start the conversation.
  4. In the onNuiAudioStateChanged callback, start the recording device based on the audio state.
  5. Continuously provide recording data in the onNuiNeedAudioData callback, or continuously push recording data through nui_update_audio_data.
  6. Continuously obtain the voice data returned by the model in the onNuiAssistEventCallback callback.
  7. Listen for events and obtain event information in the onNuiEventCallback callback.
  8. Call nui_dialog_cancel to stop the conversation, and confirm that the conversation has ended by listening for the EVENT_TRANSCRIBER_COMPLETE event.
  9. When the conversation feature is no longer used, call the nui_release method to release the SDK resources.

Request parameters

Connection and control options

Configure by passing a JSON string in the parameters parameter of the nui_initialize method.

Parameter example: The following is a JSON string example, which does not list all parameters. Add them based on your actual needs when coding:

The example uses qwen-audio-3.1-realtime-plus. To use another model, update both model in the URL and nls_config.model in Voice conversation parameters.

{
    "url": "wss://dashscope.aliyuncs.com/api-ws/v1/realtime?model=qwen-audio-3.1-realtime-plus",
    "apikey": "st-****",
    "device_id": "my_device_id",
    "service_mode": "1"
}
Parameter descriptions
ParameterTypeRequiredDescription

url

String

Yes

Service endpoint:

  • wss://dashscope.aliyuncs.com/api-ws/v1/realtime?model=<model_name>
  • China (Beijing): wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/realtime?model=<model_name>
  • Singapore: wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime?model=<model_name>
When calling, replace {WorkspaceId} with your actual Workspace ID.

apikey

String

Yes

API Key.

service_mode

String

Yes

Runtime mode. Fixed to "1" for real-time voice conversation.

device_id

String

Yes

A unique string that identifies the end user, which can be set to an in-app user ID or a client-generated unique device identifier. This ID is mainly used for log tracing and troubleshooting.

audio_update_manually

String

No

Whether to enable the active audio data push mode. Default: "false".
When it is set to "true" to enable the active audio data push mode, and the SDK version supports on-device audio capabilities (such as AEC and VAD), those capabilities are enabled by default.

workspace

String

No

The storage path of on-device resource files. This parameter must be set when audio_update_manually is set to "true" and an on-device audio capability (such as AEC or VAD) is enabled.

debug_path

String

No

The storage path of log files. This parameter takes effect only when save_log is set to YES when calling the nui_initialize method. In this case, you must set the log file path; otherwise, an error is returned. At most two log files are retained locally.

save_wav

String

No

Whether to save audio files for debugging. The audio files are saved under debug_path. Default: "false".
Valid values:

  • "true": Yes
  • "false": No
This parameter takes effect only when save_log is set to true when calling the nui_initialize method. In addition, debug_path must also be set.

max_log_file_size

int

No

The maximum number of bytes of the log file. This parameter takes effect only when save_log is set to YES when calling the nui_initialize method. Default: 104857600 (100 × 1024 × 1024 bytes, i.e., 100MiB).

log_track_level

int

No

Controls the filter level of the log content sent out through the log callback (onNuiLogTrackCallback).
Default: 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 (indicates that this feature is disabled)
Note: log_track_level and level (set through the nui_initialize method) jointly determine the logs that are finally called back. A log is called back only when its level value is greater than or equal to 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 and above (value >= 3) are called back.

Voice conversation parameters

Configure by passing a JSON string in the params parameter of the nui_set_params method.

Parameter example: The following is a JSON string example, which does not list all parameters. Add them based on your actual needs when coding:

{
    "service_type": 4,
    "nls_config": {
        "model": "qwen-audio-3.1-realtime-plus",
        "sr_format": "pcm"
    }
}
Parameter descriptions
Top-level parameterTypeRequiredDescription

service_type

int

Yes

Voice service type. Fixed to 4 for real-time voice conversation.

nls_config

object

Yes

The core voice conversation configuration object, containing key parameters such as model selection and conversation effect control.

nls_config.model

string

Yes

Specifies the model name. Supports the qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flash, qwen-audio-3.0-realtime-plus, and qwen-audio-3.0-realtime-flash model series.

nls_config.sr_format

string

Yes

Input audio format. Currently, only pcm (16kHz 16bit mono) is supported, which is the default value.

nls_config.modalities

string

No

A string in array format. Model output modality settings. Valid values:

  • ["text"]: text output only.
  • ["audio", "text"] (default): outputs both text and audio.

nls_config.voice

string

No

TTS voice name. The default value is longanqian_v3.1 for 3.1 Plus/Flash and longanqian for 3.0 Plus/Flash. It can be set only in the first session.update; values passed in afterwards will be ignored.

  • System voices for 3.1 Plus/Flash: Valid values include longanqian_v3.1 and all voices in the voice lists for 3.1 TTS Plus/Flash. For the complete range, see Voice configuration.
  • System voices for 3.0 Plus/Flash: longanqian, longanlingxin, longanlingxi, longanxiaoxin, longanlufeng.
  • Cloned voices: Created through the voice cloning API. Fill the returned voice_id into this parameter. See Voice configuration for details.

nls_config.enable_speech_emotion

BOOL

No

Whether to enable the emotion enhancement feature. When enabled, the emotional changes of the response voice are more noticeable. Default: YES. Valid values: YES and NO.

nls_config.instructions

string

No

System instructions, used to set the model's role identity, response style, and behavioral preferences. Takes effect for the entire session.

nls_config.max_history_turns

int

No

The maximum number of historical QA turns allowed in a single request. The value range is 1-50, and the default value is 20.

nls_config.tools

string

No

A string in array format. A list of Function Calling tool definitions. After configuration, the model can autonomously decide whether to call a tool based on the user input.
Internal parameter descriptions:
typestring(required)
Fixed to function.
function.namestring(required)
The name of the tool function.
function.descriptionstring(optional)
A description of what the tool function does, based on which the model determines whether to call the tool.
function.parametersobject(optional)
A description of the input parameters of the tool function, based on which the model extracts the required input parameters. If the function takes no parameters, this can be omitted.
Example:

[
  {
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "查询指定城市的天气信息。",
      "parameters": {
        "type": "object",
        "properties": {
          "city": {
            "type": "string",
            "description": "城市"
          }
        },
        "required": [
          "city"
        ]
      }
    }
  }
]

nls_config.turn_detection

string

No

The following turn detection field descriptions apply to qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flash, qwen-audio-3.0-realtime-plus, and qwen-audio-3.0-realtime-flash.

A string in JSON object format. Turn detection configuration. If it is not set, the mode switches to push-to-talk (manually committing audio and triggering inference); otherwise, duplex conversation mode is enabled.

nls_config.turn_detection.type

string

No

VAD type. Valid values:

  • server_vad (default): detects the start and end of speech based on acoustic features and automatically triggers inference.
  • smart_turn: intelligent turn detection that integrates acoustic perception and semantic understanding, determining turn boundaries through dual acoustic and semantic judgment. Sounds without semantics (such as "uh" and "ah") will not trigger a conversation turn or interrupt model playback.
  • smart_turn_v2 (recommended): enhances conversation context understanding based on smart_turn to better determine interaction intent in multi-speaker scenarios. It reduces false replies and false interruptions caused by bystander speech or irrelevant interjections.

nls_config.turn_detection.threshold

float

No

VAD sensitivity. Applies to server_vad, smart_turn, and smart_turn_v2. The lower the value, the more likely it is to recognize weak sounds (including background noise) as speech; the higher the value, the clearer and louder the speech required to trigger detection.
The value range is [-1.0, 1.0], and the default value is 0.5.

nls_config.turn_detection.silence_duration_ms

int

No

The minimum silence duration after the speech ends (in milliseconds), effective only in server_vad mode (invalid in smart_turn and smart_turn_v2 modes). When the silence reaches this duration, the model response is triggered. The lower the value, the faster the response, but a brief pause may also falsely trigger it.
The value range is [200, 6000], and the default value is 800. 400-800 is recommended for conversation scenarios.

nls_config.turn_detection.voiceprint_audio_urls

string

No

A string in array format. Effective in smart_turn and smart_turn_v2 modes. A list of publicly accessible URLs of the target user's prerecorded audio, used for speaker enhancement. The model uses these audio clips to lock onto the target speaker in the duplex conversation, ignoring the voices of others and background noise. Up to 5 URLs are supported. Audio format requirements: 16kHz PCM or WAV.

API reference

NeoNui

nui_initialize

Initializes the voice conversation SDK instance. The SDK uses singleton mode. Do not initialize it again before calling nui_release.

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

parameters

char*

A JSON string containing authentication, connection, and debugging parameters. See Connection and control parameters.

level

NuiSdkLogLevel

Controls the print level of the SDK's own logs.

save_log

BOOL

Whether to save local logs. If it is YES, you must specify a path through debug_path in the Connection and control parameters, and you can set the file size through max_log_file_size.

nui_set_params

Sets the voice conversation parameters in JSON format. Call it before nui_dialog_start.

Method signature
- (NuiResultCode) nui_set_params:(const char *)params;
Parameter descriptions
ParameterTypeDescription

params

char*

Voice conversation parameters.

nui_dialog_start

Starts the conversation.

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

vad_mode

NuiVadMode

VAD mode. Fixed to MODE_P2T.

dialog_params

char*

If the apikey parameter in the Connection and control parameters uses a temporary API Key, you can update it here when it expires.
The content is in JSON format:

{
  "apikey": "st-****"
}

nui_dialog_cancel

Ends the conversation or immediately cancels the current interaction.

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

force

BOOL

Whether to forcibly end the task and ignore the final result.

  • YES: ends the task immediately without waiting for the server to return the final recognition result.
  • NO: ends the task, but waits for the complete result to be returned.

nui_dialog_action

Sends conversation action commands during the interaction, used to update runtime behaviors such as the conversation context.

Method signature
- (NuiResultCode) nui_dialog_action:(const char *)params;
Parameter descriptions
ParameterTypeDescription

params

char*

A JSON string used to update runtime behaviors such as the conversation context.

params.type

String

Fixed to "action".

params.command

String

The specific runtime command. Currently, function_call, play_start, and play_over are supported.

  • function_call: the command to update a function call request.
  • play_start: when on-device AEC is used, notifies the SDK's internal AEC player through this command that audio playback has started.
  • play_over: when on-device AEC is used, notifies the SDK's internal AEC player through this command that audio playback has ended.

params.context

String

When command is "function_call", updates the function call request.

params.context.type

String

Event type, which must be set when command is "function_call".

  • conversation.item.create: manually inserts a conversation item into the conversation context. It can be used to inject historical context, add supplementary text information, or write back the tool execution results of Function Calling.
  • response.create: after the conversation.item.create command is sent, triggers a second round of inference through this command.

params.context.item

object

Must be set when params.context.type is conversation.item.create, representing the conversation item to create. See below for details.

params.context.response

object

Can be set when params.context.type is response.create, representing the session default configuration used to override this round of inference. If it is not passed, the current session configuration is used. See below for details.

context.item parameters:

ParameterTypeDescription

id

String

Optional. The unique identifier of the conversation item. If it is not passed, it is generated automatically by the server. If the specified ID already exists in the conversation, an error is returned.

type

String

Required. The conversation item type. Valid values:

  • message: a regular conversation message.
  • function_call: a function call request. Usually generated by the server; the client can also use it to supplement historical context.
  • function_call_output: the tool execution result. After receiving function_call, the client executes the tool and uses this type to write back the result.

role

String

Required for the message type. The message role. Valid values: system, user, assistant.

content

array

Required for the message type. The message content list. Each element contains type and the corresponding data field.
Content types supported by each role:
system
input_text: system message, with required field text.
user

  • input_text: user text input, with required field text.
  • input_audio: user audio input, with required field audio (Base64 encoded).
assistant
output_text: assistant text output, with required field text.

call_id

String

(function_call / function_call_output types, required)
The unique identifier of the function call, used to associate the request and the result.

name

String

(function_call type, required)
The name of the function to call.

arguments

String

function_call type, required)
Function call parameters, in JSON string format.

output

String

(function_call_output type, required)
The tool execution result, in JSON string format.

context.response parameters:

ParameterTypeDescription

modalities

array

A string in array format. Model output modality settings. Valid values:

  • ["text"]: text output only.
  • ["audio", "text"] (default): outputs both text and audio.

voice

string

Overrides the TTS voice for this round.

Example:

{
  "type": "action",
  "command": "function_call",
  "context": {
    "item": {
      "call_id": "call_xxxx",
      "output": "{\"city\":\"杭州\",\"condition\":\"晴\",\"temperature\":18}",
      "type": "function_call_output"
    },
    "type": "conversation.item.create"
  }
}

{
  "type": "action",
  "command": "function_call",
  "context": {
    "response": {
      "modalities": [
        "text",
        "audio"
      ]
    },
    "type": "response.create"
  }
}

nui_update_audio_data

When audio_update_manually is set to "true", recording data is no longer filled in through onNuiNeedAudioData; instead, it is actively pushed through this method.

Method signature
- (NuiResultCode) nui_update_audio_data:(const char *)data
                                    Len:(int)length
                              FirstPack:(BOOL)first_pack;
Parameter descriptions
ParameterTypeDescription

data

const char *

The pushed audio data.

length

int

The number of bytes of the pushed audio data.

first_pack

BOOL

You do not need to pay attention to this parameter.

nui_push_reference_data

When audio_update_manually is set to "true" and the on-device AEC echo cancellation capability is enabled, you need to push the audio data played by the player as the reference signal through this method.

Method signature
- (NuiResultCode) nui_push_reference_data:(const char *)data
                                     Len:(int)length
                               FirstPack:(BOOL)first_pack;
Parameter descriptions
ParameterTypeDescription

data

const char *

The pushed audio data.

length

int

The number of bytes of the pushed audio data.

first_pack

BOOL

You do not need to pay attention to this parameter.

nui_release

Releases all internal SDK resources and forcibly terminates all ongoing tasks. After this method is called, the SDK instance becomes unavailable. To use it again, you must call nui_initialize again for initialization.

Method signature
- (NuiResultCode) nui_release;

nui_get_version

Obtains the current SDK version information. This method returns a value only when it is called after nui_initialize.

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

The current SDK version information.

nui_get_all_response

Obtains the complete information of the current event callback.

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

The complete event information in JSON string format.

NeoNuiSdkDelegate: callback listeners

onNuiEventCallback: listen for event information

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

nuiEvent

NuiCallbackEvent

Callback event.

dialog

long

Session code. You do not need to pay attention to this parameter.

wuw

char*

Voice wake-up function. You do not need to pay attention to this parameter.

asr_result

char*

Speech recognition result.

finish

BOOL

Flag indicating whether this round of recognition has ended.

code

int

Valid only when the EVENT_ASR_ERROR event occurs.

onNuiAudioStateChanged: listen for the audio state

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

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

STATE_OPEN

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

STATE_PAUSE

The interaction has stopped. You can stop recording.

STATE_CLOSE

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

onNuiNeedAudioData: fill in the audio data to be processed

After the conversation starts, this callback is triggered continuously, and you must provide the audio data to be processed in it. You can ignore this callback when the audio_update_manually parameter is set to "true".

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

audioData

char *

The audio data to fill in.

len

int

The number of bytes of the filled audio data.

onNuiAssistEventCallback: auxiliary data and information results

This callback is used to receive auxiliary events and related data from inside the SDK.

Method signature
- (void) onNuiAssistEventCallback:(NuiCallbackEvent)nuiEvent
                            info:(char*)info
                         infoLen:(int)info_len
                          buffer:(char*)buffer
                             len:(int)len;
Parameter descriptions
ParameterTypeDescription

nuiEvent

NuiCallbackEvent

Callback event.

info

char *

You do not need to pay attention to this parameter.

info_len

int

You do not need to pay attention to this parameter.

buffer

char *

Auxiliary data, such as the TTS audio returned by the model.

len

int

The number of bytes of the auxiliary data.

onNuiLogTrackCallback: listen for tracking logs

This callback is used to receive detailed internal logs of the SDK, making it easier to locate and debug issues.

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

NuiCallbackEvent: event types

EventDescription

EVENT_TRANSCRIBER_STARTED

The task started successfully.

EVENT_VAD_START

Triggered immediately after the task starts. It does not mean that the start of speech has been detected.

EVENT_VAD_END

The end of speech was detected.

EVENT_ASR_PARTIAL_RESULT

An intermediate speech recognition result.

EVENT_ASR_ERROR

An error occurred during the voice conversation.

EVENT_MIC_ERROR

Triggered because no audio data has been received for 2 consecutive seconds.

EVENT_SENTENCE_END

The end of a sentence was detected, and a complete recognition result is returned at this point.

EVENT_TRANSCRIBER_COMPLETE

The voice conversation has ended.

EVENT_AUDIO_TRANSCRIPTION

An incremental text subtitle event in audio mode, returning subtitle fragments in streaming mode.

EVENT_AUDIO_TRANSCRIPTION_COMPLETED

The subtitle output completion event in audio mode.

EVENT_OTHER_RESULT

Other uncategorized event information, such as the return results of function_call.

EVENT_ASR_TTS_START

The model starts returning TTS data.

EVENT_ASR_TTS_DATA

The TTS data returned by the model.

EVENT_ASR_TTS_COMPLETE

The model has finished returning TTS data.

EVENT_AEC_DATA

The audio data after AEC echo cancellation.