Skip to main content

Qwen-LiveTranslate-Realtime C# SDK

Use the C# SDK to call Qwen-LiveTranslate-Realtime over WebSocket and translate speech into text and audio in the target language.

Prerequisites

Get an API key and set DASHSCOPE_API_KEY. Use an API key from the same region as your workspace.

Install the SDK

Download and extract Bailian.DashScope-1.1.0.zip. To use the SDK in a C# project, install it from the local NuGet source.

Quick start

Run the bundled example

  1. Create a .NET 10 console project and install the SDK as described above.
  2. 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 workspace WebSocket endpoint. Replace WorkspaceId with your workspace ID. For supported regions and endpoints, see WebSocket access.
export DASHSCOPE_REALTIME_URL="wss://WorkspaceId.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime"

Call the SDK in a project

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 QwenLiveTranslator(new QwenLiveTranslateOptions
{
    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"],
    SourceLanguage = "zh",
    TargetLanguage = "en",
    SampleRate = 16000,
});

using var output = File.Create("output.pcm");
var completed = new TaskCompletionSource<string?>(TaskCreationOptions.RunContinuationsAsynchronously);
client.TranslationCompleted += (_, e) => Console.WriteLine(e.Text);
client.TranslatedAudioChunk += (_, 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);
}

await client.FinishAsync(ct);
var status = await completed.Task.WaitAsync(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 qwen3.8-livetranslate-flash-realtime Serena

Request parameters

OptionTypeDefaultDescription
ApiKeystring?nullModel Studio API key. If omitted, the SDK reads DASHSCOPE_API_KEY.
Urlstringwss://dashscope.aliyuncs.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. To use a workspace-specific endpoint, set the full address in Url.
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.
Modelstringqwen3.5-livetranslate-flash-realtimeModel ID.
ModalitiesIList<string>["text", "audio"]Output modalities. Use ["text"] for translated text only.
Voicestring?nullVoice for translated audio. If omitted, the server chooses a default. When generating audio with 3.8, specify a voice supported by that model.
EnableVoiceClonebool?nullEnables voice cloning for translated audio.
VoiceCloneFrequencystringonceonce clones the voice at the start of the session, always clones it for each sentence, and never uses an existing cloned voice ID. Check which modes your model supports.
SampleRateint16000Input sample rate in Hz. Choose a sample rate supported by your model.
InputAudioFormatstringpcmInput audio format. The SDK option accepts pcm or opus. Check the client event reference for the formats your model supports.
OutputAudioFormatstring?nullOutput audio format, such as pcm. When omitted, the server uses its default.
TranscriptionModelstring?qwen3-asr-flash-realtimeModel for source speech recognition. With qwen3.5-livetranslate-flash-realtime, set both this option and SourceLanguage to null to omit input_audio_transcription. Source speech recognition is always enabled in 3.8.
SourceLanguagestring?nullSource language code, such as zh. When omitted, the server detects the language.
TargetLanguagestringenTarget language code, such as en.
SkipSameLanguageTextbool?nullSkips the translated text when the source and target languages match. Check whether your model version supports this option.
SkipSameLanguageAudiobool?nullSkips translated audio when the source and target languages match. Check whether your model version supports this option.
CorpusPhrasesIDictionary<string, string>?nullTranslation glossary that maps source terms to target terms in translation.corpus.phrases.
VadThresholddouble?0.5Server VAD threshold from -1.0 to 1.0.
VadSilenceMsint1000Silence duration in milliseconds before the server detects the end of speech.
EnableDebugInfobool?nullRequests debug information from the server.
For audio and video translation with 3.8, first set session.input_modalities to ["audio", "video"] as shown in WebSocket access, then send image frames alongside audio. AppendImageAsync sends image frames. Use SendRawEventAsync to send complete client events for fields without a dedicated SDK option.

API reference

Use DashScope.Qwen.QwenLiveTranslator with QwenLiveTranslateOptions. Some session settings and event fields differ between 3.5 and 3.8. See the client event reference for your model.

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.
AppendImageAsync(string imageBase64, CancellationToken ct = default)Sends a Base64 image frame in input_image_buffer.append. Select a model that supports image input and enable audio and image input first.
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.

Events

EventEvent argumentWhen it fires
SessionReadystring?The session is ready. The value is session.id.
SourceTranscriptUpdatedQwenTranscriptEventArgsCurrent source transcript. Returned when source speech recognition is enabled.
SourceTranscriptCompletedQwenTranscriptEventArgsFinal transcript of a source utterance.
TranslationTextDeltaQwenTextDeltaEventArgsTranslation delta. Read TranslationCompleted for the final translation.
TranslationCompletedQwenTranscriptEventArgsComplete translation for the utterance.
TranslatedAudioChunkQwenAudioChunkEventArgsTranslated audio chunk. The format and sample rate depend on the session configuration and the model response.
TranslatedAudioCompletedEventArgsAll translated audio for the turn has arrived.
ResponseCompletedQwenResponseSummaryresponse.done arrived with status and usage.
RawServerEventQwenServerEventArgsRaw server event with its type and JSON object.
ErrorOccurredDashScopeErrorEventArgsA server error or connection failure occurred.
See C# SDK result types for the event argument fields. Translation usage is cumulative for the session.

Ending the session

After sending all audio, call FinishAsync to end the session and receive any remaining translation and translated audio. LiveTranslate defaults to FinishAndWait, which sends session.finish and waits for session.finished.