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
- 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.
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
| Option | Type | Default | Description |
|---|---|---|---|
ApiKey | string? | null | Model Studio API key. If omitted, the SDK reads DASHSCOPE_API_KEY. |
Url | string | wss://dashscope.aliyuncs.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. To use a workspace-specific endpoint, set the full address in Url. |
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 | qwen3.5-livetranslate-flash-realtime | Model ID. |
Modalities | IList<string> | ["text", "audio"] | Output modalities. Use ["text"] for translated text only. |
Voice | string? | null | Voice for translated audio. If omitted, the server chooses a default. When generating audio with 3.8, specify a voice supported by that model. |
EnableVoiceClone | bool? | null | Enables voice cloning for translated audio. |
VoiceCloneFrequency | string | once | once 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. |
SampleRate | int | 16000 | Input sample rate in Hz. Choose a sample rate supported by your model. |
InputAudioFormat | string | pcm | Input audio format. The SDK option accepts pcm or opus. Check the client event reference for the formats your model supports. |
OutputAudioFormat | string? | null | Output audio format, such as pcm. When omitted, the server uses its default. |
TranscriptionModel | string? | qwen3-asr-flash-realtime | Model 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. |
SourceLanguage | string? | null | Source language code, such as zh. When omitted, the server detects the language. |
TargetLanguage | string | en | Target language code, such as en. |
SkipSameLanguageText | bool? | null | Skips the translated text when the source and target languages match. Check whether your model version supports this option. |
SkipSameLanguageAudio | bool? | null | Skips translated audio when the source and target languages match. Check whether your model version supports this option. |
CorpusPhrases | IDictionary<string, string>? | null | Translation glossary that maps source terms to target terms in translation.corpus.phrases. |
VadThreshold | double? | 0.5 | Server VAD threshold from -1.0 to 1.0. |
VadSilenceMs | int | 1000 | Silence duration in milliseconds before the server detects the end of speech. |
EnableDebugInfo | bool? | null | Requests 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.
| 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. |
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
| Event | Event argument | When it fires |
|---|---|---|
SessionReady | string? | The session is ready. The value is session.id. |
SourceTranscriptUpdated | QwenTranscriptEventArgs | Current source transcript. Returned when source speech recognition is enabled. |
SourceTranscriptCompleted | QwenTranscriptEventArgs | Final transcript of a source utterance. |
TranslationTextDelta | QwenTextDeltaEventArgs | Translation delta. Read TranslationCompleted for the final translation. |
TranslationCompleted | QwenTranscriptEventArgs | Complete translation for the utterance. |
TranslatedAudioChunk | QwenAudioChunkEventArgs | Translated audio chunk. The format and sample rate depend on the session configuration and the model response. |
TranslatedAudioCompleted | EventArgs | All translated audio for the turn has arrived. |
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. |
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.