Communitygithub.com

microsoft/azure-ai-voicelive-dotnet

Azure KI Voice Live SDK für .NET. Entwickeln Sie Echtzeit-Sprach-KI-Anwendungen mit bidirektionaler WebSocket-Kommunikation. Ideal für Sprachassistenten, konversationelle KI, Echtzeit-Sprache-zu-Sprache und sprachgesteuerte Chatbots.

Was ist azure-ai-voicelive-dotnet?

Das Azure.AI.VoiceLive SDK für .NET ermöglicht Entwicklern die Erstellung von Echtzeit-Sprach-KI-Anwendungen mit bidirektionaler WebSocket-Kommunikation. Es unterstützt Szenarien wie Sprachassistenten, konversationelle KI, Echtzeit-Sprache-zu-Sprache-Übersetzung und sprachgesteuerte Chatbots. Das SDK kann über NuGet installiert werden und arbeitet mit Azure KI Services zusammen, wobei es Authentifizierung mittels Microsoft Entra Token oder API-Schlüssel unterstützt. Die Kernarchitektur besteht aus einem VoiceLiveClient, der VoiceLiveSession-Instanzen erstellt – jede Session repräsentiert eine WebSocket-Verbindung und ermöglicht das Konfigurieren von Sprachmodellen (z. B. gpt-4o-realtime-preview), Voice Activity Detection (VAD), Audioformaten und Funktionen. Entwickler können Benutzernachrichten senden, Audio-Streams verarbeiten, Ereignisse wie Audio-Deltas oder Text-Deltas abonnieren und Funktionsaufrufe (Function Calling) integrieren. Das SDK unterstützt mehrere Modelle, darunter GPT-4o und GPT-4o-mini für Echtzeit-Audio, sowie verschiedene Sprachoptionen (Standard, HD, Custom) und kann plattformübergreifend mit NAudio für Audio-Capture/Playback eingesetzt werden.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-voicelive-dotnet

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Azure.AI.VoiceLive (.NET)

Echtzeit-Sprach-KI SDK für die Entwicklung bidirektionaler Sprachassistenten mit Azure KI.

Installation

dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio                    # Für Audio-Aufnahme/Wiedergabe

Aktuelle Versionen: Stabil v1.0.0, Vorschau v1.1.0-beta.1

Umgebungsvariablen

AZURE_VOICELIVE_ENDPOINT=https://<resource>.services.ai.azure.com/  # Erforderlich: Voice Live Endpunkt
AZURE_VOICELIVE_MODEL=gpt-4o-realtime-preview  # Erforderlich: Modell-Bereitstellungsname
AZURE_VOICELIVE_VOICE=en-US-AvaNeural  # Optional: Voice Live Stimmenname
AZURE_VOICELIVE_API_KEY=<your-api-key>  # Nur erforderlich für AzureKeyCredential-Authentifizierung
AZURE_TOKEN_CREDENTIALS=prod  # Nur erforderlich, wenn DefaultAzureCredential in der Produktion verwendet wird

Authentifizierung

Microsoft Entra Token-Anmeldeinformationen

using Azure.Identity;
using Azure.AI.VoiceLive;

Uri endpoint = new Uri("https://ihre-resource.cognitiveservices.azure.com");
// Lokale Entwicklung: DefaultAzureCredential. Produktion: set AZURE_TOKEN_CREDENTIALS=prod oder AZURE_TOKEN_CREDENTIALS=<bestimmte_Anmeldeinformation>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Oder verwenden Sie direkt eine bestimmte Anmeldeinformation in der Produktion:
// Siehe https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);

Erforderliche Rolle: Cognitive Services User (im Azure-Portal → Zugriffssteuerung zuweisen)

API-Schlüssel

Uri endpoint = new Uri("https://ihre-resource.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("ihr-api-key");
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);

Client-Hierarchie

VoiceLiveClient
└── VoiceLiveSession (WebSocket-Verbindung)
    ├── ConfigureSessionAsync()
    ├── GetUpdatesAsync() → SessionUpdate-Ereignisse
    ├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
    ├── SendAudioAsync()
    └── StartResponseAsync()

Kern-Workflow

1. Sitzung starten und konfigurieren

using Azure.Identity;
using Azure.AI.VoiceLive;

var endpoint = new Uri(Environment.GetEnvironmentVariable("AZURE_VOICELIVE_ENDPOINT"));
var client = new VoiceLiveClient(endpoint, new DefaultAzureCredential());

var model = "gpt-4o-mini-realtime-preview";

// Sitzung starten
using VoiceLiveSession session = await client.StartSessionAsync(model);

// Sitzung konfigurieren
VoiceLiveSessionOptions sessionOptions = new()
{
    Model = model,
    Instructions = "Sie sind ein hilfreicher KI-Assistent. Antworten Sie natürlich.",
    Voice = new AzureStandardVoice("en-US-AvaNeural"),
    TurnDetection = new AzureSemanticVadTurnDetection()
    {
        Threshold = 0.5f,
        PrefixPadding = TimeSpan.FromMilliseconds(300),
        SilenceDuration = TimeSpan.FromMilliseconds(500)
    },
    InputAudioFormat = InputAudioFormat.Pcm16,
    OutputAudioFormat = OutputAudioFormat.Pcm16
};

// Modalitäten festlegen (sowohl Text als auch Audio für Sprachassistenten)
sessionOptions.Modalities.Clear();
sessionOptions.Modalities.Add(InteractionModality.Text);
sessionOptions.Modalities.Add(InteractionModality.Audio);

await session.ConfigureSessionAsync(sessionOptions);

2. Ereignisse verarbeiten

await foreach (SessionUpdate serverEvent in session.GetUpdatesAsync())
{
    switch (serverEvent)
    {
        case SessionUpdateResponseAudioDelta audioDelta:
            byte[] audioData = audioDelta.Delta.ToArray();
            // Audio über NAudio oder andere Audio-Bibliothek abspielen
            break;
            
        case SessionUpdateResponseTextDelta textDelta:
            Console.Write(textDelta.Delta);
            break;
            
        case SessionUpdateResponseFunctionCallArgumentsDone functionCall:
            // Funktionsaufruf behandeln (siehe Abschnitt Function Calling)
            break;
            
        case SessionUpdateError error:
            Console.WriteLine($"Fehler: {error.Error.Message}");
            break;
            
        case SessionUpdateResponseDone:
            Console.WriteLine("\n--- Antwort abgeschlossen ---");
            break;
    }
}

3. Benutzernachricht senden

await session.AddItemAsync(new UserMessageItem("Hallo, können Sie mir helfen?"));
await session.StartResponseAsync();

4. Funktionen aufrufen (Function Calling)

// Funktion definieren
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
    Description = "Ruft das aktuelle Wetter für einen bestimmten Ort ab",
    Parameters = BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "Die Stadt und das Bundesland oder Land"
                }
            },
            "required": ["location"]
        }
        """)
};

// Zu den Sitzungsoptionen hinzufügen
sessionOptions.Tools.Add(weatherFunction);

// Funktionsaufruf in der Ereignisschleife behandeln
if (serverEvent is SessionUpdateResponseFunctionCallArgumentsDone functionCall)
{
    if (functionCall.Name == "get_current_weather")
    {
        var parameters = JsonSerializer.Deserialize<Dictionary<string, string>>(functionCall.Arguments);
        string location = parameters?["location"] ?? "";
        
        // Externen Dienst aufrufen
        string weatherInfo = $"Das Wetter in {location} ist sonnig, 24°C.";
        
        // Antwort senden
        await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
        await session.StartResponseAsync();
    }
}

Sprachoptionen

SprachtypKlasseBeispiel
Azure StandardAzureStandardVoice"en-US-AvaNeural"
Azure HDAzureStandardVoice"en-US-Ava:DragonHDLatestNeural"
Azure CustomAzureCustomVoiceBenutzerdefinierte Stimme mit Endpunkt-ID

Unterstützte Modelle

ModellBeschreibung
gpt-4o-realtime-previewGPT-4o mit Echtzeit-Audio
gpt-4o-mini-realtime-previewLeichtgewichtig, schnelle Interaktionen
phi4-mm-realtimeKosteneffizient multimodal

Referenz wichtiger Typen

TypZweck
VoiceLiveClientHauptclient zum Erstellen von Sitzungen
VoiceLiveSessionAktive WebSocket-Sitzung
VoiceLiveSessionOptionsSitzungskonfiguration
AzureStandardVoiceStandard-Azure-Sprachprovider
AzureSemanticVadTurnDetectionSpracherkennung
VoiceLiveFunctionDefinitionFunktionswerkzeug-Definition
UserMessageItemBenutzertextnachricht
FunctionCallOutputItemFunktionsaufruf-Antwort
SessionUpdateResponseAudioDeltaAudio-Chunk-Ereignis
SessionUpdateResponseTextDeltaText-Chunk-Ereignis

Best Practices

  1. Immer beide Modalitäten setzen — Fügen Sie Text und Audio für Sprachassistenten hinzu
  2. AzureSemanticVadTurnDetection verwenden — Ermöglicht natürlichen Gesprächsfluss
  3. Angemessene Stille-Dauer konfigurieren — typischerweise 500ms, um vorzeitige Abbrüche zu vermeiden
  4. using-Anweisung verwenden — Stellt ordnungsgemäße Sitzungsfreigabe sicher
  5. Alle Ereignistypen behandeln — Überprüfen Sie auf Fehler, Audio, Text und Funktionsaufrufe
  6. DefaultAzureCredential verwenden — Niemals API-Schlüssel hartcodieren

Fehlerbehandlung

if (serverEvent is SessionUpdateError error)
{
    if (error.Error.Message.Contains("Cancellation failed: no active response"))
    {
        // Harmloser Fehler, kann ignoriert werden
    }
    else
    {
        Console.WriteLine($"Fehler: {error.Error.Message}");
    }
}

Audio-Konfiguration

  • Eingabeformat: InputAudioFormat.Pcm16 (16-Bit PCM)
  • Ausgabeformat: OutputAudioFormat.Pcm16
  • Abtastrate: 24 kHz empfohlen
  • Kanäle: Mono

Verwandte SDKs

SDKZweckInstallation
Azure.AI.VoiceLiveEchtzeit-Sprache (dieses SDK)dotnet add package Azure.AI.VoiceLive
Microsoft.CognitiveServices.SpeechSprache-zu-Text, Text-zu-Sprachedotnet add package Microsoft.CognitiveServices.Speech
NAudioAudio-Aufnahme/Wiedergabedotnet add package NAudio

Referenzlinks

RessourceURL
NuGet-Pakethttps://www.nuget.org/packages/Azure.AI.VoiceLive
API-Referenzhttps://learn.microsoft.com/dotnet/api/azure.ai.voicelive
GitHub-Quellcodehttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.VoiceLive
Schnellstarthttps://learn.microsoft.com/azure/ai-services/speech-service/voice-live-quickstart

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

Verwandte Skills