Use the C# SDK to stream audio to Qwen-Audio-Realtime over WebSocket and receive text and audio responses.
Install the SDK
Download and extract Bailian.DashScope-1.1.0.zip. The SDK targets net8.0 and net10.0. Run the following command from your project directory, using the path to the extracted packages/ directory.
DashScope.dll from the extracted sdk/net8.0/ or sdk/net10.0/ directory that matches your target framework. Keep DashScope.xml next to the DLL to see API documentation in your IDE.
Quickstart
- Get an API key and set
DASHSCOPE_API_KEY. Use an API key from the same region as your workspace. - Create a .NET 10 console project and install the SDK as described above.
- Place
input.pcmin the project directory. Use 16 kHz, mono, 16-bit little-endian raw PCM. Convert WAV files to raw PCM first.
C# example
This program streams a raw PCM recording in real time, waits for the response to complete, and writes the audio to output.pcm. Replace Program.cs with the following code.
API reference
Audio Realtime and Omni Realtime both use DashScope.Qwen.QwenRealtimeConversation. Pass QwenRealtimeConversationOptions to the constructor. The default points to an Audio Realtime model. To use Omni, set an Omni model ID explicitly.
Connection and session options
| Option | Type | Default | Description |
|---|---|---|---|
ApiKey | string? | null | QwenCloud API key. If omitted, the SDK reads DASHSCOPE_API_KEY. |
Url | string | wss://ap-southeast-1.maas.qwencloudapi.com/api-ws/v1/realtime | WebSocket endpoint. The SDK appends Model as the model query parameter. |
WorkspaceId | string? | null | Workspace ID sent in the X-DashScope-WorkSpace header. |
ConnectTimeout | TimeSpan | 10 s | Timeout for opening the WebSocket connection. |
StartTimeout | TimeSpan | 10 s | Timeout for receiving session.created. |
StopTimeout | TimeSpan | 10 s | Timeout for receiving session.finished when the finish mode waits for that event. |
FinishMode | QwenRealtimeFinishMode? | null | When omitted, the SDK chooses a finish mode based on the model. Read FinishMode on the instance to see which mode it uses. |
Model | string | qwen-audio-3.1-realtime-plus | Model ID. For Omni, set this explicitly to the desired Omni Realtime model. |
Modalities | IList<string> | ["text", "audio"] | Output modalities. Use ["text"] for text-only output. |
Voice | string? | null | Voice for audio output. null leaves the choice to the server. The Audio 3.1 example sets longanfengyue_v3.1 explicitly. |
EnableSpeechEmotion | bool? | null | Enables emotional speech where supported. See the client event reference for the model. |
Instructions | string? | null | System instructions. |
MaxHistoryTurns | int? | null | Number of conversation turns to retain, from 1 to 50. |
ToolsJson | string? | null | Function tool definitions as an OpenAI-style tools JSON array string. |
TurnDetectionMode | QwenTurnDetectionMode | ServerVad | Turn detection mode. ServerVad detects speech boundaries on the server. Some models support SmartTurn. With PushToTalk, the client commits the audio and requests a response. |
VadThreshold | double? | null | Server VAD threshold from -1.0 to 1.0. Applies to ServerVad. |
VadSilenceMs | int? | null | End-of-speech silence duration, from 200 to 6,000 milliseconds. Applies to ServerVad. When omitted, the model uses its server default. |
Methods
The methods below return Task, except for DisposeAsync. ct is an optional cancellation token.
| Method | Description |
|---|---|
ConnectAsync(CancellationToken ct = default) | Opens the connection, waits for session.created, and sends session.update. |
AppendAudioAsync(ReadOnlyMemory<byte> pcm, CancellationToken ct = default) | Sends an audio frame. The SDK Base64-encodes the bytes and sends an input_audio_buffer.append event. |
CommitAudioAsync(CancellationToken ct = default) | Commits buffered audio with input_audio_buffer.commit in PushToTalk mode. |
CreateResponseAsync(JsonObject? responseOptions = null, CancellationToken ct = default) | Requests a response with response.create. responseOptions supplies optional overrides for the current response. |
SendItemAsync(JsonObject item, CancellationToken ct = default) | Adds item to the conversation using conversation.item.create. |
SendFunctionCallOutputAsync(string callId, string outputJson, CancellationToken ct = default) | Returns tool results using the callId from the event and the output JSON string. |
SendRawEventAsync(string frameJson, CancellationToken ct = default) | Sends the complete client event JSON as provided. Use this method for events without a dedicated SDK method. |
FinishAsync(CancellationToken ct = default) | Ends the session using the active FinishMode. |
AbortAsync() | Closes the connection immediately and discards pending results. |
DisposeAsync() | Releases resources asynchronously and returns a ValueTask. |
PushToTalk mode, call CommitAudioAsync and then CreateResponseAsync after sending audio. To handle a tool call, run the tool after FunctionCallReceived and return its result. Call CreateResponseAsync again if the model should continue responding.
Events
| Event | Event argument | When it fires |
|---|---|---|
SessionReady | string? | The session is ready. The value is session.id. |
UserSpeechStarted | QwenSpeechEventArgs | Server VAD detected the start of user speech. |
UserSpeechStopped | QwenSpeechEventArgs | Server VAD detected the end of user speech. |
UserTranscriptUpdated | QwenTranscriptEventArgs | Current input transcript, which may change. |
UserTranscriptCompleted | QwenTranscriptEventArgs | Final transcript of an input utterance. |
AssistantTextDelta | QwenTextDeltaEventArgs | Response text delta. Concatenate deltas in order. |
AssistantTextCompleted | QwenTranscriptEventArgs | Complete response text. |
AssistantAudioChunk | QwenAudioChunkEventArgs | Response audio chunk in 24 kHz mono 16-bit little-endian raw PCM. |
AssistantAudioCompleted | EventArgs | All response audio for the turn has arrived. |
FunctionCallReceived | QwenFunctionCallEventArgs | The model requested a tool call and supplied the call ID, function name, and JSON arguments. |
ResponseCompleted | QwenResponseSummary | response.done arrived with status and usage. |
RawServerEvent | QwenServerEventArgs | Raw server event with its type and JSON object. |
ErrorOccurred | DashScopeErrorEventArgs | A server error or connection failure occurred. |
Result types
| Type | Properties | Description |
|---|---|---|
QwenResponseSummary | Status: string?, FailureReason: string?, TotalTokens: int?, InputTokens: int?, OutputTokens: int?, AudioInputTokens: int?, AudioOutputTokens: int? | Response status, failure reason, and usage. Status can be completed, failed, or incomplete. Conversation usage is per turn. Translation usage is cumulative for the session. |
QwenSpeechEventArgs | AudioMs: long, ItemId: string? | Speech boundary in milliseconds and the input item ID. |
QwenTranscriptEventArgs | Text: string, ItemId: string? | Current transcript or final text and the item ID. |
QwenTextDeltaEventArgs | Delta: string, ItemId: string? | Text delta and the item ID. |
QwenAudioChunkEventArgs | Pcm: byte[] | Audio chunk. |
QwenFunctionCallEventArgs | CallId: string, Name: string?, ArgumentsJson: string? | Tool call ID, name, and arguments. Use the original CallId when returning the result. |
QwenServerEventArgs | Type: string?, Root: JsonObject | Event type and full JSON. |
DashScopeErrorEventArgs | Code: int, ServerErrorCode: string?, ServerErrorMessage: string?, TaskId: string?, InnerException: Exception? | SDK error code, server error code and message, task or session ID, and the underlying exception. |
Ending the session
Reuse the connection for multiple conversation turns. Call FinishAsync after the final ResponseCompleted event to avoid truncating the response.
| Finish mode | Behavior |
|---|---|
FinishWithoutWait | Sends session.finish and closes the connection. This is the default for Audio Realtime. |
CloseOnly | Closes the connection. This is the default for Omni Realtime. |
FinishAndWait | Sends session.finish and waits for session.finished. The server can also end the session by closing the connection. |