C# SDK Methods and events

Updated at:

Client class reference for the Bailian.DashScope SDK, covering methods, events, properties, and result objects for speech recognition, speech synthesis, real-time voice conversation, and real-time translation.

FunAsrSpeechTranscriber

Methods

ct (CancellationToken, optional): cancels the current asynchronous call.

MethodReturnsDescription

StartAsync(CancellationToken ct = default)

Task

Connect and wait for task-started.

SendAudioAsync(ReadOnlyMemory<byte> pcmFrame, CancellationToken ct = default)

Task

Send an audio frame after startup.

StopAsync(CancellationToken ct = default)

Task

Send finish-task and await the final results and task-finished. Repeated calls reuse the completed task.

CancelAsync()

Task

Immediately close the connection. Repeated calls are allowed.

TranscribePcmStreamAsync(Stream pcm, int frameMilliseconds = 20, CancellationToken ct = default)

Task<IReadOnlyList<RecognitionSentence>>

Read a PCM stream, send frames, and return final sentences. Frames default to 20 ms.

DisposeAsync()

ValueTask

Release client resources.

SendContextAsync(JsonArray context, CancellationToken ct = default)

Task

Qwen-Audio-ASR-Message: Send the protocol context array.

Events

EventTypeDescription

TranscriberStarted

EventHandler

Task started.

SentenceBegin

EventHandler<RecognitionSentenceEventArgs>

Sentence start.

PartialResult

EventHandler<RecognitionSentenceEventArgs>

Intermediate recognition result.

SentenceEnd

EventHandler<RecognitionSentenceEventArgs>

Final recognition result for a sentence.

Completed

EventHandler<TranscriptionCompletedEventArgs>

Task finished.

Failed

EventHandler<DashScopeErrorEventArgs>

Task failure or unexpected disconnection.

Results

Read usage in RawPayload for the usage fields returned by the model. The compatibility duration field may be absent from completion events.

PropertyTypeDescription

FunAsrSpeechTranscriber.TaskId

string

Identifier.

RecognitionSentenceEventArgs

PropertyTypeDescription

Sentence

RecognitionSentence

Sentence details.

RawPayload

JsonObject?

Original response JSON.

RecognitionSentence

PropertyTypeDescription

SentenceId

int

Identifier.

BeginTimeMs

long

Start time in milliseconds.

EndTimeMs

long?

End time in milliseconds; may be absent before finalization.

Text

string

Text.

IsBegin

bool

Whether this is a sentence start.

IsEnd

bool

Whether this is the final result for a sentence.

ChannelId

int

Audio channel index; channel numbering starts at 0.

SpeakerId

string?

Speaker identifier.

Words

IReadOnlyList<RecognitionWord>

Word details.

StashText

string?

Stashed recognition text.

RequestId

string?

Identifier.

RecognitionWord

PropertyTypeDescription

BeginTimeMs

long

Start time in milliseconds.

EndTimeMs

long?

End time in milliseconds; may be absent before finalization.

Text

string

Text.

Punctuation

string

Punctuation.

Fixed

bool?

Whether the word is finalized.

SpeakerId

string?

Speaker identifier.

TranscriptionCompletedEventArgs

PropertyTypeDescription

UsageDurationSeconds

float?

Audio duration in seconds (usage.duration).

RawPayload

JsonObject?

Original response JSON.

CosyVoiceSpeechSynthesizer

Methods

ct (CancellationToken, optional): cancels the current asynchronous call.

MethodReturnsDescription

StartAsync(CancellationToken ct = default)

Task

Connect and wait for task-started.

SendTextAsync(string text, CancellationToken ct = default)

Task

Append a text segment after startup.

StopAsync(CancellationToken ct = default)

Task

Send finish-task and await the final results and task-finished. Repeated calls reuse the completed task.

CancelSynthesisKeepConnectionAsync(CancellationToken ct = default)

Task

Cancel synthesis with input.directive=cancel and wait for task-finished, without actively closing the connection.

CancelAsync()

Task

Immediately close the connection. Repeated calls are allowed.

StreamAudioAsync(IEnumerable<string> segments, TimeSpan? sendInterval = null, CancellationToken ct = default)

IAsyncEnumerable<ReadOnlyMemory<byte>>

Send text segments and yield audio chunks. sendInterval=null uses 200 ms; TimeSpan.Zero sends without waiting.

SynthesizeAsync(IEnumerable<string> segments, TimeSpan? sendInterval = null, CancellationToken ct = default)

Task<byte[]>

Collect all audio from StreamAudioAsync into one byte array; the same sendInterval rules apply.

DisposeAsync()

ValueTask

Release client resources.

Events

EventTypeDescription

SynthesisStarted

EventHandler

Task started.

AudioReceived

EventHandler<ReadOnlyMemory<byte>>

Audio bytes in order; append chunks to form the output file.

SentenceProgress

EventHandler<SynthesisSentenceEventArgs>

Sentence synthesis progress: begin, synthesis, and end.

SynthesisCompleted

EventHandler

Task finished.

Failed

EventHandler<DashScopeErrorEventArgs>

Task failure or unexpected disconnection.

Results

PropertyTypeDescription

CosyVoiceSpeechSynthesizer.TaskId

string

Identifier.

CosyVoiceSpeechSynthesizer.Usage

SynthesisUsage?

Qwen-Audio-TTS: Final task usage. After SynthesizeAsync or StopAsync returns, read InputTokens, OutputTokens, and TotalTokens for the input, output, and total token counts, and Characters for the character count. Usage is null if the server returns no usage. qwen-audio-3.1-tts-flash is billed by token; qwen-audio-3.1-tts-plus is billed by character but also returns token counts.

CosyVoice: Final task usage. After SynthesizeAsync or StopAsync returns, read Characters for the total character count. Usage is null if the server returns no usage.

SynthesisSentenceEventArgs

PropertyTypeDescription

Phase

SynthesisSentencePhase

Begin / Synthesis / End. Sentence synthesis progress: begin, synthesis, and end.

SentenceIndex

int

Identifier.

OriginalText

string?

Original input text.

NormalizedText

string?

Normalized synthesis text.

BilledCharacters

int?

usage.characters returned by the service.

Words

JsonNode?

Word details.

SambertSpeechSynthesizer

Methods

ct (CancellationToken, optional): cancels the current asynchronous call.

MethodReturnsDescription

StartAsync(string text, CancellationToken ct = default)

Task

Send the complete text and wait for task-started.

WaitFinishedAsync(CancellationToken ct = default)

Task

Wait for server-driven completion; Sambert does not use finish-task.

CancelAsync()

Task

Immediately close the connection. Repeated calls are allowed.

StreamAudioAsync(string text, CancellationToken ct = default)

IAsyncEnumerable<ReadOnlyMemory<byte>>

Submit the complete text and yield audio chunks until completion.

SynthesizeAsync(string text, CancellationToken ct = default)

Task<byte[]>

Submit the complete text and return all audio as a byte array.

DisposeAsync()

ValueTask

Release client resources.

Events

EventTypeDescription

SynthesisStarted

EventHandler

Task started.

AudioReceived

EventHandler<ReadOnlyMemory<byte>>

Audio bytes in order; append chunks to form the output file.

SentenceTimestamps

EventHandler<SambertSentenceEventArgs>

Word and phoneme timestamps when enabled.

SynthesisCompleted

EventHandler

Task finished.

Failed

EventHandler<DashScopeErrorEventArgs>

Task failure or unexpected disconnection.

Results

PropertyTypeDescription

SambertSpeechSynthesizer.TaskId

string?

Identifier.

SambertSpeechSynthesizer.Usage

SynthesisUsage?

Final task usage. After SynthesizeAsync or WaitFinishedAsync returns, read Characters for the total character count. Usage is null if the server returns no usage.

SambertSentenceEventArgs

PropertyTypeDescription

BeginTimeMs

int?

Start time in milliseconds.

EndTimeMs

int?

End time in milliseconds; may be absent before finalization.

Words

JsonNode?

Word details. With PhonemeTimestampEnabled and WordTimestampEnabled enabled, each word can include a phonemes array.

BilledCharacters

int?

usage.characters returned by the service.

FunAsrFileTranscriber

In the DashScope.Transcription namespace, used for asynchronous submission, polling, and result download of recorded audio transcription (Qwen-Audio-ASR-Flash-Filetrans, Fun-ASR, and Paraformer).

Methods

ct (CancellationToken, optional): cancels the current asynchronous call.

MethodReturnsDescription

SubmitAsync(FileTranscriptionRequest request, CancellationToken ct = default)

Task<FileTranscriptionSubmission>

Submits an asynchronous transcription task and returns TaskId immediately without waiting for completion.

QueryAsync(string taskId, CancellationToken ct = default)

Task<FileTranscriptionResult>

Queries the current status and subtask list of a task once.

WaitForCompletionAsync(string taskId, IProgress<FileTranscriptionResult>? status = null, TimeSpan? timeout = null, TimeSpan? pollInterval = null, CancellationToken ct = default)

Task<FileTranscriptionResult>

Polls until the task reaches a terminal state (Succeeded, Failed, or Canceled), or throws on timeout.

DownloadTranscriptionAsync(string transcriptionUrl, CancellationToken ct = default)

Task<TranscriptionFile>

Downloads and parses the transcription result JSON file from a subtask TranscriptionUrl.

TranscribeAsync(FileTranscriptionRequest request, IProgress<FileTranscriptionResult>? status = null, CancellationToken ct = default)

Task<IReadOnlyList<FileTranscriptionOutput>>

Submits, polls, and downloads all succeeded subtask results in one call; throws if the overall task fails or all subtasks fail.

CancelTaskAsync(string taskId, CancellationToken ct = default)

Task

Cancels a queued task (only supported while Pending).

Dispose()

void

Releases the underlying HTTP client resources.

Result objects

FileTranscriptionSubmission

PropertyTypeDescription
RequestIdstringRequest ID.
TaskIdstringAsynchronous task ID (valid for 24 hours).
TaskStatusFunAsrTaskStatusCurrent task status.
RawJsonObject?Raw submission response JSON.

FileTranscriptionResult

PropertyTypeDescription
RequestIdstring?Request ID.
TaskIdstringAsynchronous task ID.
TaskStatusFunAsrTaskStatusTask status.
IsTerminalboolWhether the task has reached a terminal state (Succeeded, Failed, or Canceled).
Codestring?Error code when the overall task fails.
Messagestring?Error message when the overall task fails.
SubmitTimestring?Task submission timestamp.
ScheduledTimestring?Task scheduling timestamp.
EndTimestring?Task completion timestamp.
UsageDurationSecondslong?Billed audio duration in seconds.
ResultsIReadOnlyList<FileTranscriptionSubtask>Subtask results; check each subtask's SubtaskStatus even when the overall task is Succeeded.
RawJsonObject?Raw query response JSON.

FileTranscriptionSubtask

PropertyTypeDescription
FileUrlstringSource audio URL.
SubtaskStatusFunAsrTaskStatusSubtask status.
TranscriptionUrlstring?Temporary download URL for the transcription result JSON (valid for 24 hours).
Codestring?Subtask error code when failed.
Messagestring?Subtask error message when failed.

FileTranscriptionOutput

PropertyTypeDescription
SubtaskFileTranscriptionSubtaskSubtask metadata.
TranscriptionTranscriptionFileDownloaded and parsed transcription result file.

TranscriptionFile

PropertyTypeDescription
FileUrlstringSource audio URL.
PropertiesTranscriptionAudioProperties?Source audio properties.
TranscriptsIReadOnlyList<TranscriptChannel>Per-channel transcription results.
RawJsonObject?Raw result file JSON.

TranscriptionAudioProperties

PropertyTypeDescription
AudioFormatstring?Audio encoding format (such as pcm_s16le).
ChannelsIReadOnlyList<int>Channel index list.
OriginalSamplingRateint?Original sample rate in Hz.
OriginalDurationMslong?Original audio duration in milliseconds.

TranscriptChannel

PropertyTypeDescription
ChannelIdintAudio channel index.
ContentDurationMslongSpeech content duration in milliseconds.
TextstringFull concatenated transcript for the channel.
SentencesIReadOnlyList<TranscriptSentence>Sentence-level results.

TranscriptSentence

PropertyTypeDescription
SentenceIdintSentence sequence number.
BeginTimeMslongStart time in milliseconds.
EndTimeMslongEnd time in milliseconds.
TextstringSentence text.
SpeakerIdint?Speaker index (returned when speaker diarization is enabled).
WordsIReadOnlyList<TranscriptWord>Word-level timestamps.

TranscriptWord

PropertyTypeDescription
BeginTimeMslongWord start time in milliseconds.
EndTimeMslongWord end time in milliseconds.
TextstringWord text.
PunctuationstringTrailing punctuation.

FunAsrFlashFileTranscriber

In the DashScope.Transcription namespace, used for synchronous or SSE streaming recorded audio transcription (Qwen-Audio-ASR-Flash and Fun-ASR-Flash).

Methods

ct (CancellationToken, optional): cancels the current asynchronous call.

MethodReturnsDescription

TranscribeAsync(FlashTranscriptionRequest request, CancellationToken ct = default)

Task<FlashTranscriptionResult>

Performs a single synchronous transcription request and returns the final result.

TranscribeStreamingAsync(FlashTranscriptionRequest request, CancellationToken ct = default)

IAsyncEnumerable<FlashTranscriptionResult>

Streams interim and final sentence results frame by frame via SSE.

Dispose()

void

Releases the underlying HTTP client resources.

Result objects

FlashTranscriptionResult

PropertyTypeDescription
RequestIdstringRequest ID.
TextstringFull recognized text.
SentenceFlashSentenceCurrent sentence result (updated per frame in streaming mode).
UsageDurationSecondslong?Processed audio duration in seconds.
RawJsonObject?Raw response JSON.

FlashSentence

PropertyTypeDescription
SentenceIdintSentence sequence number.
SentenceEndboolWhether this is the final result for the sentence.
BeginTimeMslongSentence start time in milliseconds.
EndTimeMslong?Sentence end time in milliseconds (returned only when SentenceEnd is true).
TextstringSentence text.
ChannelIdintChannel index.
WordsIReadOnlyList<FlashWord>Word-level timestamps.

FlashWord

PropertyTypeDescription
BeginTimeMslongWord start time in milliseconds.
EndTimeMslong?Word end time in milliseconds.
TextstringWord text.
PunctuationstringTrailing punctuation.
Fixedbool?When false, timestamps may still be adjusted in subsequent interim frames.

QwenRealtimeConversation

In the DashScope.Qwen namespace, used for real-time voice conversation with Qwen-Audio-Realtime and Qwen-Omni-Realtime.

Methods

ct (CancellationToken, optional): cancels the current asynchronous call.

MethodReturnsDescription
ConnectAsync(CancellationToken ct = default)TaskConnects, waits for session.created, and sends session.update.
AppendAudioAsync(ReadOnlyMemory<byte> pcm, CancellationToken ct = default)TaskSends a PCM audio frame (Base64-encoded internally as input_audio_buffer.append).
CommitAudioAsync(CancellationToken ct = default)TaskCommits the audio buffer with input_audio_buffer.commit in PushToTalk mode.
CreateResponseAsync(JsonObject? responseOptions = null, CancellationToken ct = default)TaskSends response.create to request a response; responseOptions overrides per-turn settings.
SendItemAsync(JsonObject item, CancellationToken ct = default)TaskAdds an item to the conversation using conversation.item.create.
SendFunctionCallOutputAsync(string callId, string outputJson, CancellationToken ct = default)TaskReturns tool execution output using the original callId and JSON result.
SendRawEventAsync(string frameJson, CancellationToken ct = default)TaskSends a raw client event JSON frame.
FinishAsync(CancellationToken ct = default)TaskGracefully ends the session according to FinishMode.
AbortAsync()TaskImmediately closes the connection and discards in-flight results.
DisposeAsync()ValueTaskAsynchronously releases client resources.

Events

EventTypeTrigger
SessionReadyEventHandler<string?>Session is ready; argument is session.id.
UserSpeechStartedEventHandler<QwenSpeechEventArgs>Server VAD detected start of user speech.
UserSpeechStoppedEventHandler<QwenSpeechEventArgs>Server VAD detected end of user speech.
UserTranscriptUpdatedEventHandler<QwenTranscriptEventArgs>Interim transcript of user speech.
UserTranscriptCompletedEventHandler<QwenTranscriptEventArgs>Final transcript of a user speech utterance.
AssistantTextDeltaEventHandler<QwenTextDeltaEventArgs>Incremental assistant response text.
AssistantTextCompletedEventHandler<QwenTranscriptEventArgs>Complete assistant response text.
AssistantAudioChunkEventHandler<QwenAudioChunkEventArgs>Assistant audio chunk (24 kHz mono 16-bit little-endian raw PCM).
AssistantAudioCompletedEventHandlerAll assistant audio for the current turn has been delivered.
FunctionCallReceivedEventHandler<QwenFunctionCallEventArgs>Model requests a tool call.
ResponseCompletedEventHandler<QwenResponseSummary>Received response.done with status and usage.
RawServerEventEventHandler<QwenServerEventArgs>Raw server event.
ErrorOccurredEventHandler<DashScopeErrorEventArgs>Server error or connection failure.

Properties

PropertyTypeDescription
SessionIdstring?Server session ID.
FinishModeQwenRealtimeFinishModeActual finish mode used for the session.

Result objects

QwenResponseSummary

PropertyTypeDescription
Statusstring?Response status (completed, failed, or incomplete).
FailureReasonstring?Failure reason.
TotalTokensint?Total tokens (per turn for conversation; session cumulative for translation).
InputTokensint?Input tokens.
OutputTokensint?Output tokens.
AudioInputTokensint?Audio input tokens.
AudioOutputTokensint?Audio output tokens.

QwenSpeechEventArgs

PropertyTypeDescription
AudioMslongSpeech start or stop offset in milliseconds.
ItemIdstring?Item ID.

QwenTranscriptEventArgs

PropertyTypeDescription
TextstringCurrent or final transcript text.
ItemIdstring?Item ID.

QwenTextDeltaEventArgs

PropertyTypeDescription
DeltastringIncremental text chunk.
ItemIdstring?Item ID.

QwenAudioChunkEventArgs

PropertyTypeDescription
Pcmbyte[]Audio chunk bytes.

QwenFunctionCallEventArgs

PropertyTypeDescription
CallIdstringTool call ID; pass the original value when returning output.
Namestring?Tool name.
ArgumentsJsonstring?Tool arguments JSON string.

QwenServerEventArgs

PropertyTypeDescription
Typestring?Server event type.
RootJsonObjectFull event JSON object.

QwenLiveTranslator

In the DashScope.Qwen namespace, used for real-time speech and audio-video translation with Qwen-LiveTranslate-Realtime.

Methods

ct (CancellationToken, optional): cancels the current asynchronous call.

MethodReturnsDescription
ConnectAsync(CancellationToken ct = default)TaskConnects, waits for session.created, and sends session.update.
AppendAudioAsync(ReadOnlyMemory<byte> pcm, CancellationToken ct = default)TaskSends a PCM audio frame (Base64-encoded internally as input_audio_buffer.append).
AppendImageAsync(string imageBase64, CancellationToken ct = default)TaskSends a Base64-encoded image frame as input_image_buffer.append.
SendRawEventAsync(string frameJson, CancellationToken ct = default)TaskSends a raw client event JSON frame.
FinishAsync(CancellationToken ct = default)TaskGracefully ends the session according to FinishMode.
AbortAsync()TaskImmediately closes the connection and discards in-flight results.
DisposeAsync()ValueTaskAsynchronously releases client resources.

Events

EventTypeTrigger
SessionReadyEventHandler<string?>Session is ready; argument is session.id.
SourceTranscriptUpdatedEventHandler<QwenTranscriptEventArgs>The source transcript was updated.
SourceTranscriptCompletedEventHandler<QwenTranscriptEventArgs>Final transcript of a source speech utterance.
TranslationTextDeltaEventHandler<QwenTextDeltaEventArgs>The translation text was updated.
TranslationCompletedEventHandler<QwenTranscriptEventArgs>Complete translated text for the sentence.
TranslatedAudioChunkEventHandler<QwenAudioChunkEventArgs>Translated audio chunk.
TranslatedAudioCompletedEventHandlerAll translated audio for the current turn has been delivered.
ResponseCompletedEventHandler<QwenResponseSummary>Received response.done with status and session cumulative usage.
RawServerEventEventHandler<QwenServerEventArgs>Raw server event.
ErrorOccurredEventHandler<DashScopeErrorEventArgs>Server error or connection failure.

Properties

PropertyTypeDescription
SessionIdstring?Server session ID.
FinishModeQwenRealtimeFinishModeActual finish mode used for the session.

Result objects

QwenTranscriptEventArgs

PropertyTypeDescription
TextstringIn SDK 1.1.1, SourceTranscriptUpdated returns the current transcript for qwen3.5-livetranslate-flash-realtime but can return an empty string for qwen3.8-livetranslate-flash-realtime. SourceTranscriptCompleted returns the final source transcript for the sentence, and TranslationCompleted returns its full translation.
ItemIdstring?Item ID.

QwenTextDeltaEventArgs

PropertyTypeDescription
DeltastringFor qwen3.5-livetranslate-flash-realtime, interim translations can repeat. Do not concatenate them; read TranslationCompleted.Text for the full translation. For qwen3.8-livetranslate-flash-realtime, response.text.delta contains new text that you can append in arrival order.
ItemIdstring?Item ID.

QwenAudioChunkEventArgs

PropertyTypeDescription
Pcmbyte[]PCM bytes of the translated audio. The sample rate depends on the session configuration and the audio returned by the server.

QwenResponseSummary

PropertyTypeDescription
Statusstring?Response status, such as completed, failed, or incomplete.
FailureReasonstring?Reason for failure; null on successful completion.
TotalTokensint?Total tokens accumulated in the current session.
InputTokensint?Input tokens.
OutputTokensint?Output tokens.
AudioInputTokensint?Audio input tokens.
AudioOutputTokensint?Audio output tokens.

QwenServerEventArgs

PropertyTypeDescription
Typestring?Server event type.
RootJsonObjectComplete server event as a JSON object.

Shared types

DashScope.DashScopeErrorEventArgs

PropertyTypeDescription

Code

int

SDK error code

ServerErrorCode

string?

Server error code

ServerErrorMessage

string?

Server error message

TaskId

string?

ID of the current task

InnerException

Exception?

Underlying exception

DashScope.Speech.SynthesisUsage

PropertyTypeDescription

InputTokens

int?

Input tokens

OutputTokens

int?

Output tokens

TotalTokens

int?

Total tokens

Characters

int?

Character count returned by the server

DashScope.Transcription.FunAsrTaskStatus

MemberDescription
PendingQueued.
RunningProcessing.
SucceededSucceeded.
FailedFailed.
CanceledCanceled.
UnknownTask does not exist or status is unknown.

DashScope.Qwen.QwenTurnDetectionMode

MemberDescription
ServerVadServer detects speech start and end.
SmartTurnSemantic turn detection (supported by some models).
PushToTalkClient calls CommitAudioAsync and CreateResponseAsync to control turns.

DashScope.QwenRealtimeFinishMode

MemberDescription
FinishWithoutWaitSends session.finish and disconnects immediately.
CloseOnlyCloses the connection directly.
FinishAndWaitSends session.finish and waits for session.finished.