AssemblyAI has an official .NET SDK available,
and we use this SDK primarily to improve the overall experience
of our SDK/try to reach/exceed the level of the official one and
extend it to all our generated SDKs for other platforms.
usingAssemblyAI;usingvarapi=newAssemblyAIClient(apiKey);varfileUrl="https://github.com/AssemblyAI-Community/audio-examples/raw/main/20230607_me_canadian_wildfires.mp3";//// You can also transcribe a local file by passing in a file path// var filePath = "./path/to/file.mp3";// var uploadedFile = await api.Files.UploadAsync(await File.ReadAllBytesAsync(filePath));// fileUrl = uploadedFile.UploadUrl;varqueued=awaitapi.Transcripts.SubmitAsync(TranscriptParams.FromUrl(fileUrl,newTranscriptOptionalParams{SpeechModels=[SpeechModel2.Universal35Pro],LanguageDetection=true,// Enables native code-switching routing.SpeakerLabels=true,// Speaker diarization.Prompt="Canadian wildfire news interview with air quality and public health terms.",KeytermsPrompt=["Peter DeCarlo","Johns Hopkins","particulate matter"],}));Transcripttranscript;do{awaitTask.Delay(TimeSpan.FromSeconds(2));transcript=awaitapi.Transcripts.GetAsync(queued.Id.ToString());}while(transcript.StatusisTranscriptStatus.QueuedorTranscriptStatus.Processing);transcript.EnsureStatusCompleted();Console.WriteLine(transcript);
usingvarclient=GetAuthenticatedApi();varfileUrl="https://github.com/AssemblyAI-Community/audio-examples/raw/main/20230607_me_canadian_wildfires.mp3";// You can also transcribe a local file by uploading bytes first:// var apiKey = Environment.GetEnvironmentVariable("ASSEMBLYAI_API_KEY")!;// var uploaded = await client.Files.UploadAsync(apiKey, await File.ReadAllBytesAsync("./path/to/file.mp3"));// fileUrl = uploaded.UploadUrl!;varqueued=awaitclient.Transcripts.SubmitAsync(TranscriptParams.FromUrl(fileUrl,newTranscriptOptionalParams{SpeechModels=[SpeechModel2.Universal35Pro],LanguageDetection=true,SpeakerLabels=true,AutoHighlights=true,}));// Submit returns immediately; poll Transcripts.GetAsync until the status is Completed (or Error).vartranscript=awaitPollUntilTerminalAsync(client,queued.Id);transcript.EnsureStatusCompleted();
Transcribe Live
Connect to the AssemblyAI v3 real-time streaming API for live speech-to-text transcription.
varapiKey=Environment.GetEnvironmentVariable("ASSEMBLYAI_API_KEY")is{Length:>0}apiKeyValue?apiKeyValue:thrownewAssertInconclusiveException("ASSEMBLYAI_API_KEY environment variable is not found.");// Create the realtime client and connect with API-key auth (Authorization header).usingvarclient=newAssemblyAIRealtimeClient();awaitclient.ConnectAsync(apiKey,newStreamingConnectOptions{SpeechModel=StreamingSpeechModel.Universal35ProRealtime,FormatTurns=true,AgentContext="Thanks for calling Contoso support. What is your email address?",VoiceFocus=StreamingVoiceFocus.NearField,SpeakerLabels=true,MaxSpeakers=2,});// Receive the session started event.usingvarcts=newCancellationTokenSource(TimeSpan.FromSeconds(30));varreceivedSessionBegins=false;awaitforeach(varserverEventinclient.ReceiveUpdatesAsync(cts.Token)){if(serverEvent.IsBegin){receivedSessionBegins=true;Console.WriteLine($"Session started: {serverEvent.Begin?.Id}");Console.WriteLine($"Expires at: {serverEvent.Begin?.ExpiresAt}");// After the session starts, send audio data.// In a real application, you would stream microphone PCM16 audio:// await client.SendAsync(new ArraySegment<byte>(audioBytes), WebSocketMessageType.Binary, true, cts.Token);// Update configuration for turn detection sensitivity.awaitclient.SendUpdateConfigurationAsync(newUpdateConfigurationPayload{AgentContext="Got it. Could you spell the account ID?",Mode=UpdateConfigurationPayloadMode.Balanced,MaxTurnSilence=2000,});// For this example, manually force an endpoint to get results.awaitclient.SendForceEndpointAsync(newForceEndpointPayload());break;}}// Gracefully terminate the session.awaitclient.SendSessionTerminationAsync(newSessionTerminationPayload());
Speech To Text Client Get Text Async
1 2 3 4 5 6 7 8 910111213141516
usingvarclient=GetAuthenticatedApi();ISpeechToTextClientspeechClient=client;// Transcribe audio using the MEAI ISpeechToTextClient interface.// The client uploads the audio stream and polls until transcription is complete.usingvarhttpClient=newHttpClient();awaitusingvaraudioStream=awaithttpClient.GetStreamAsync("https://github.com/AssemblyAI-Community/audio-examples/raw/main/20230607_me_canadian_wildfires.mp3");varms=newMemoryStream();awaitaudioStream.CopyToAsync(ms);ms.Position=0;varresponse=awaitspeechClient.GetTextAsync(ms);Console.WriteLine($"Text: {response.Text}");
Speech To Text Client Get Service Metadata
12345
usingvarclient=newAssemblyAIClient("dummy-key");ISpeechToTextClientspeechClient=client;// Retrieve metadata about the speech-to-text provider.varmetadata=speechClient.GetService<SpeechToTextClientMetadata>();
Speech To Text Client Get Service Self
12345
usingvarclient=newAssemblyAIClient("dummy-key");ISpeechToTextClientspeechClient=client;// Access the underlying AssemblyAIClient from the MEAI interface.varself=speechClient.GetService<AssemblyAIClient>();