Skip to main content
WebSocket

Qwen-Audio-Realtime C# SDK

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.
dotnet add package Bailian.DashScope --version 1.1.0 --source "/path/to/Bailian.DashScope-1.1.0/packages"
You can also reference 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

  1. Get an API key and set DASHSCOPE_API_KEY. Use an API key from the same region as your workspace.
  2. Create a .NET 10 console project and install the SDK as described above.
  3. Place input.pcm in the project directory. Use 16 kHz, mono, 16-bit little-endian raw PCM. Convert WAV files to raw PCM first.
Set the Singapore endpoint. For supported regions and endpoints, see WebSocket access.
# Singapore (ap-southeast-1). For another region, replace ap-southeast-1 in the URL.
# API keys are region-specific. See https://docs.qwencloud.com/developer-guides/getting-started/regions
export DASHSCOPE_REALTIME_URL="wss://ap-southeast-1.maas.qwencloudapi.com/api-ws/v1/realtime"

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.
using DashScope.Qwen;

if (args.Length < 2)
    throw new ArgumentException("Usage: <input.pcm> <model> [voice]");

using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60));
var ct = timeout.Token;
await using var client = new QwenRealtimeConversation(new QwenRealtimeConversationOptions
{
    Model = args[1],
    Voice = args.Length > 2 ? args[2] : null,
    Url = Environment.GetEnvironmentVariable("DASHSCOPE_REALTIME_URL")
        ?? throw new InvalidOperationException("Set DASHSCOPE_REALTIME_URL to your workspace WebSocket endpoint."),
    Modalities = ["text", "audio"],
    TurnDetectionMode = QwenTurnDetectionMode.ServerVad,
});

using var output = File.Create("output.pcm");
var completed = new TaskCompletionSource<string?>(TaskCreationOptions.RunContinuationsAsynchronously);
client.AssistantTextCompleted += (_, e) => Console.WriteLine(e.Text);
client.AssistantAudioChunk += (_, e) => output.Write(e.Pcm);
client.ResponseCompleted += (_, e) => completed.TrySetResult(e.Status);
client.ErrorOccurred += (_, e) => completed.TrySetException(
    new InvalidOperationException($"{e.ServerErrorCode}: {e.ServerErrorMessage}"));

await client.ConnectAsync(ct);
using var input = File.OpenRead(args[0]);
var frame = new byte[640];
int size;
while ((size = await input.ReadAsync(frame.AsMemory(), ct)) > 0)
{
    await client.AppendAudioAsync(frame.AsMemory(0, size), ct);
    await Task.Delay(20, ct);
}

Array.Clear(frame);
for (var i = 0; i < 60; i++)
{
    await client.AppendAudioAsync(frame, ct);
    await Task.Delay(20, ct);
}

var status = await completed.Task.WaitAsync(ct);
await client.FinishAsync(ct);
if (status != "completed" || output.Length == 0)
    throw new InvalidOperationException($"Status: {status}, audio bytes: {output.Length}");
Place the raw PCM file from the quickstart in your project directory and run the example.
dotnet run -- input.pcm qwen-audio-3.1-realtime-plus longanfengyue_v3.1

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

OptionTypeDefaultDescription
ApiKeystring?nullQwenCloud API key. If omitted, the SDK reads DASHSCOPE_API_KEY.
Urlstringwss://ap-southeast-1.maas.qwencloudapi.com/api-ws/v1/realtimeWebSocket endpoint. The SDK appends Model as the model query parameter.
WorkspaceIdstring?nullWorkspace ID sent in the X-DashScope-WorkSpace header.
ConnectTimeoutTimeSpan10 sTimeout for opening the WebSocket connection.
StartTimeoutTimeSpan10 sTimeout for receiving session.created.
StopTimeoutTimeSpan10 sTimeout for receiving session.finished when the finish mode waits for that event.
FinishModeQwenRealtimeFinishMode?nullWhen omitted, the SDK chooses a finish mode based on the model. Read FinishMode on the instance to see which mode it uses.
Modelstringqwen-audio-3.1-realtime-plusModel ID. For Omni, set this explicitly to the desired Omni Realtime model.
ModalitiesIList<string>["text", "audio"]Output modalities. Use ["text"] for text-only output.
Voicestring?nullVoice for audio output. null leaves the choice to the server. The Audio 3.1 example sets longanfengyue_v3.1 explicitly.
EnableSpeechEmotionbool?nullEnables emotional speech where supported. See the client event reference for the model.
Instructionsstring?nullSystem instructions.
MaxHistoryTurnsint?nullNumber of conversation turns to retain, from 1 to 50.
ToolsJsonstring?nullFunction tool definitions as an OpenAI-style tools JSON array string.
TurnDetectionModeQwenTurnDetectionModeServerVadTurn detection mode. ServerVad detects speech boundaries on the server. Some models support SmartTurn. With PushToTalk, the client commits the audio and requests a response.
VadThresholddouble?nullServer VAD threshold from -1.0 to 1.0. Applies to ServerVad.
VadSilenceMsint?nullEnd-of-speech silence duration, from 200 to 6,000 milliseconds. Applies to ServerVad. When omitted, the model uses its server default.
For regional endpoints, see Audio Realtime WebSocket access or Omni Realtime WebSocket access.

Methods

The methods below return Task, except for DisposeAsync. ct is an optional cancellation token.
MethodDescription
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.
In 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

EventEvent argumentWhen it fires
SessionReadystring?The session is ready. The value is session.id.
UserSpeechStartedQwenSpeechEventArgsServer VAD detected the start of user speech.
UserSpeechStoppedQwenSpeechEventArgsServer VAD detected the end of user speech.
UserTranscriptUpdatedQwenTranscriptEventArgsCurrent input transcript, which may change.
UserTranscriptCompletedQwenTranscriptEventArgsFinal transcript of an input utterance.
AssistantTextDeltaQwenTextDeltaEventArgsResponse text delta. Concatenate deltas in order.
AssistantTextCompletedQwenTranscriptEventArgsComplete response text.
AssistantAudioChunkQwenAudioChunkEventArgsResponse audio chunk in 24 kHz mono 16-bit little-endian raw PCM.
AssistantAudioCompletedEventArgsAll response audio for the turn has arrived.
FunctionCallReceivedQwenFunctionCallEventArgsThe model requested a tool call and supplied the call ID, function name, and JSON arguments.
ResponseCompletedQwenResponseSummaryresponse.done arrived with status and usage.
RawServerEventQwenServerEventArgsRaw server event with its type and JSON object.
ErrorOccurredDashScopeErrorEventArgsA server error or connection failure occurred.

Result types

TypePropertiesDescription
QwenResponseSummaryStatus: 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.
QwenSpeechEventArgsAudioMs: long, ItemId: string?Speech boundary in milliseconds and the input item ID.
QwenTranscriptEventArgsText: string, ItemId: string?Current transcript or final text and the item ID.
QwenTextDeltaEventArgsDelta: string, ItemId: string?Text delta and the item ID.
QwenAudioChunkEventArgsPcm: byte[]Audio chunk.
QwenFunctionCallEventArgsCallId: string, Name: string?, ArgumentsJson: string?Tool call ID, name, and arguments. Use the original CallId when returning the result.
QwenServerEventArgsType: string?, Root: JsonObjectEvent type and full JSON.
DashScopeErrorEventArgsCode: 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 modeBehavior
FinishWithoutWaitSends session.finish and closes the connection. This is the default for Audio Realtime.
CloseOnlyCloses the connection. This is the default for Omni Realtime.
FinishAndWaitSends session.finish and waits for session.finished. The server can also end the session by closing the connection.