Examples stay source-of-truth driven. The examples below are generated from the integration test suite, so the README, docs site, and executable samples stay aligned.
List Available Voices
Fetch all voices available to the authenticated account and print each voice name and ID so you can pick one for text-to-speech requests.
1 2 3 4 5 6 7 8 910
usingvarclient=newElevenLabsClient(apiKey);// Fetch all voices for the authenticated workspace.GetVoicesResponseModelresponse=awaitclient.Voices.GetAllAsync();// Print the voice names and IDs so you can reuse a voice in text-to-speech.foreach(varvoiceinresponse.Voices){Console.WriteLine($"{voice.Name} ({voice.VoiceId})");}
Text to Speech
Pick a voice from the available catalog, synthesize text with it, and save the generated audio to disk.
1 2 3 4 5 6 7 8 9101112131415161718
usingvarclient=newElevenLabsClient(apiKey);// Choose a voice to synthesize with.varvoices=awaitclient.Voices.GetAllAsync();varvoice=voices.Voices[0];conststringtext="Hello, world! This is a test of the ElevenLabs text-to-speech API.";Console.WriteLine($"Using voice: {voice.Name} ({voice.VoiceId})");Console.WriteLine($"Input text: {text}");// Generate speech audio.byte[]audioBytes=awaitclient.TextToSpeech.ConvertAsync(voiceId:voice.VoiceId,text:text);// Persist the result to a local file.awaitFile.WriteAllBytesAsync("output.mp3",audioBytes);Console.WriteLine($"Saved {audioBytes.Length} bytes to output.mp3");
Streaming Text to Speech
Pick a voice from the available catalog, request a streaming text-to-speech response for low-latency playback, and save the returned audio stream.
1 2 3 4 5 6 7 8 9101112131415161718192021
usingvarclient=newElevenLabsClient(apiKey);// Choose a voice to synthesize with.varvoices=awaitclient.Voices.GetAllAsync();varvoice=voices.Voices[0];conststringtext="This audio is streamed for low-latency playback.";Console.WriteLine($"Using voice: {voice.Name} ({voice.VoiceId})");Console.WriteLine($"Input text: {text}");// Request streaming speech audio.usingvarstreamedAudio=awaitclient.TextToSpeech.StreamAsync(voiceId:voice.VoiceId,text:text,modelId:"eleven_multilingual_v2",outputFormat:TextToSpeechStreamOutputFormat.Mp32205032);// Persist the result to a local file.awaitusingvaroutput=File.Create("streamed-output.mp3");awaitstreamedAudio.CopyToAsync(output);Console.WriteLine($"Saved {output.Length} bytes to streamed-output.mp3");
Streaming Text to Speech with Timestamps
Pick a voice from the available catalog, then stream synthesized audio together with character-level timing information for subtitles, captions, or lip-sync.
usingvarclient=newElevenLabsClient(apiKey);// Choose a voice to synthesize with.varvoices=awaitclient.Voices.GetAllAsync();varvoice=voices.Voices[0];conststringtext="Hello, this has timestamps.";Console.WriteLine($"Using voice: {voice.Name} ({voice.VoiceId})");Console.WriteLine($"Input text: {text}");// Request streamed speech audio with timing metadata.StreamingAudioChunkWithTimestampsResponseModel?firstChunk=null;intchunkCount=0;awaitforeach(varchunkinclient.TextToSpeech.StreamWithTimestampsAsync(voiceId:voice.VoiceId,text:text,modelId:"eleven_multilingual_v2",outputFormat:TextToSpeechStreamWithTimestampsOutputFormat.Mp32205032)){firstChunk??=chunk;chunkCount++;// Inspect the alignment information when it is present.if(chunkCount==1&&chunk.Alignmentis{}alignment){for(inti=0;i<alignment.Characters?.Count;i++){Console.WriteLine($"'{alignment.Characters[i]}' "+$"{alignment.CharacterStartTimesSeconds?[i]:F3}s - "+$"{alignment.CharacterEndTimesSeconds?[i]:F3}s");}}}
Sound Generation
Generate a short sound effect from a text prompt and save the returned audio bytes.
1 2 3 4 5 6 7 8 910
usingvarclient=newElevenLabsClient(apiKey);// Generate a sound effect from a text description.byte[]soundBytes=awaitclient.TextToSoundEffects.ConvertAsync(text:"A gentle ocean wave crashing on a sandy beach",durationSeconds:3.0);// Persist the result to a local file.awaitFile.WriteAllBytesAsync("ocean-wave.mp3",soundBytes);Console.WriteLine($"Saved {soundBytes.Length} bytes to ocean-wave.mp3");
Speech to Text from a File
Transcribe a WAV file from disk and print the returned transcript text.
1 2 3 4 5 6 7 8 910111213141516171819202122
usingvarclient=newElevenLabsClient(apiKey);// Load an audio file to transcribe.byte[]audioFile=awaitFile.ReadAllBytesAsync(Path.Combine(AppContext.BaseDirectory,"Resources","hello-in-russian-24k-pcm16.wav"));// Submit the file for transcription.vartranscription=awaitclient.SpeechToText2.ConvertAsync(modelId:BodySpeechToTextV1SpeechToTextPostModelId.ScribeV1,file:audioFile,filename:"hello-in-russian-24k-pcm16.wav",languageCode:"ru");// Print the transcript text when it is available.vartranscriptText=transcription.Value1is{}chunk?chunk.Text:null;if(!string.IsNullOrWhiteSpace(transcriptText)){Console.WriteLine(transcriptText);}
Voice Cloning
Create an instant voice clone from an audio sample, print the new voice ID, and delete the test voice afterwards.
1 2 3 4 5 6 7 8 91011121314151617
usingvarclient=newElevenLabsClient(apiKey);// Load a voice sample from disk.byte[]voiceSample=awaitFile.ReadAllBytesAsync(Path.Combine(AppContext.BaseDirectory,"Resources","hello-in-russian-24k-pcm16.wav"));// Create the cloned voice.AddVoiceIVCResponseModelresponse=awaitclient.Voices.CreateAsync(name:$"Test Cloned Voice {Guid.NewGuid():N}",files:[voiceSample],description:"A cloned voice from my audio sample",removeBackgroundNoise:false);Console.WriteLine($"Cloned voice ID: {response.VoiceId}");// Clean up the test voice once the example has succeeded.awaitclient.Voices.DeleteAsync(response.VoiceId);
Realtime Speech to Text
Open a realtime transcription session, stream PCM audio in chunks, and read transcript events until a final transcript arrives.
usingvarclient=newElevenLabsClient(apiKey);usingvarcts=newCancellationTokenSource(TimeSpan.FromSeconds(30));// Open a realtime speech-to-text session.awaitusingvarsession=awaitclient.ConnectRealtimeAsync(newRealtimeSpeechToTextOptions{AudioFormat=RealtimeAudioFormat.Pcm24000,CommitStrategy=RealtimeCommitStrategy.Manual,},cancellationToken:cts.Token);// Load a WAV file and convert it to PCM16 samples.byte[]wavBytes=awaitFile.ReadAllBytesAsync(Path.Combine(AppContext.BaseDirectory,"Resources","hello-in-russian-24k-pcm16.wav"),cts.Token);var(pcm,sampleRate,channels)=ReadWavPcm16(wavBytes);// Send the audio in 0.5 second chunks and commit the final chunk.constintsamplesPerChunk=12000;for(varoffset=0;offset<pcm.Length;offset+=samplesPerChunk){varcount=Math.Min(samplesPerChunk,pcm.Length-offset);varbytes=newbyte[count*2];Buffer.BlockCopy(pcm,offset*2,bytes,0,bytes.Length);varcommit=offset+count>=pcm.Length;awaitsession.SendAudioChunkAsync(bytes,sampleRate,commit,cancellationToken:cts.Token);}// Read events until the service returns a final transcript.string?transcript=null;awaitforeach(varevtinsession.ReadEventsAsync(cts.Token)){switch(evt){caseSessionStartedEventstarted:Console.WriteLine($"Session started: {started.SessionId}");break;casePartialTranscriptEventpartial:Console.WriteLine($"Partial: {partial.Text}");break;caseCommittedTranscriptEventcommitted:transcript=committed.Text;Console.WriteLine($"Final: {committed.Text}");break;caseCommittedTranscriptWithTimestampsEventcommittedWithTimestamps:transcript=committedWithTimestamps.Text;Console.WriteLine($"Final: {committedWithTimestamps.Text}");break;caseErrorEventerror:thrownewInvalidOperationException($"ElevenLabs error: {error.ErrorType} - {error.Error}");}if(!string.IsNullOrWhiteSpace(transcript)){break;}}
Realtime STT (Generated Client)
Use the auto-generated ElevenLabsRealtimeClient to stream audio and receive typed ServerEvent events via the discriminated union pattern.
varapiKey=Environment.GetEnvironmentVariable("ELEVENLABS_API_KEY")is{Length:>0}apiKeyValue?apiKeyValue:thrownewAssertInconclusiveException("ELEVENLABS_API_KEY environment variable is not found.");// Create the generated realtime client and connect with the API key in the URL.usingvarclient=newElevenLabsRealtimeClient();awaitclient.ConnectAsync(newUri($"wss://api.elevenlabs.io/v1/speech-to-text/realtime?xi_api_key={apiKey}"));// Load a WAV file and extract raw PCM16 audio bytes.byte[]wavBytes=awaitFile.ReadAllBytesAsync(Path.Combine(AppContext.BaseDirectory,"Resources","hello-in-russian-24k-pcm16.wav"));var(pcmSamples,sampleRate,_)=ReadWavPcm16(wavBytes);// Send audio chunks using the typed SendInputAudioChunkAsync method.constintsamplesPerChunk=12000;for(varoffset=0;offset<pcmSamples.Length;offset+=samplesPerChunk){varcount=Math.Min(samplesPerChunk,pcmSamples.Length-offset);varbytes=newbyte[count*2];Buffer.BlockCopy(pcmSamples,offset*2,bytes,0,bytes.Length);varisLastChunk=offset+count>=pcmSamples.Length;awaitclient.SendInputAudioChunkAsync(newInputAudioChunkPayload{AudioBase64=Convert.ToBase64String(bytes),SampleRate=sampleRate,Commit=isLastChunk,});}// Receive typed server events via the discriminated ServerEvent union.usingvarcts=newCancellationTokenSource(TimeSpan.FromSeconds(30));varreceivedSessionStarted=false;string?sessionId=null;string?transcript=null;awaitforeach(varserverEventinclient.ReceiveUpdatesAsync(cts.Token)){if(serverEvent.IsSessionStarted){receivedSessionStarted=true;sessionId=serverEvent.SessionStarted?.SessionId;Console.WriteLine($"Session started: {sessionId}");}elseif(serverEvent.IsPartialTranscript){Console.WriteLine($"Partial: {serverEvent.PartialTranscript?.Text}");}elseif(serverEvent.IsCommittedTranscript){transcript=serverEvent.CommittedTranscript?.Text;Console.WriteLine($"Final: {transcript}");break;}elseif(serverEvent.IsCommittedTranscriptWithTimestamps){transcript=serverEvent.CommittedTranscriptWithTimestamps?.Text;Console.WriteLine($"Final (with timestamps): {transcript}");break;}elseif(serverEvent.IsError){}}