Communitygithub.com

microsoft/azure-ai-voicelive-dotnet

SDK Azure AI Voice Live pour .NET. Créez des applications vocales en temps réel avec communication WebSocket bidirectionnelle. Utilisez-le pour assister les assistants vocaux, l'IA conversationnelle, la conversion parole-parole en temps réel et les chatbots vocaux. Déclencheurs : « voice live », « real-time voice », « VoiceLiveClient », « VoiceLiveSession », « assistant vocal .NET », « audio bidirectionnel », « parole à parole ».

Qu'est-ce que azure-ai-voicelive-dotnet ?

Azure.AI.VoiceLive (.NET) est un SDK spécialisé pour construire des applications d'assistant vocal en temps réel avec l'IA Azure. Il offre une communication bidirectionnelle via WebSocket, permettant la diffusion audio en temps réel et la gestion des événements texte, audio et d'appels de fonctions. Ce SDK prend en charge le paramétrage avancé de la session (modèle, voix, détection de parole, formats audio), la gestion des erreurs, et l'intégration avec les bibliothèques audio comme NAudio. Il est idéal pour les scénarios d'assistant vocal conversationnel, de chatbot à commande vocale, et de conversion parole-à-parole en temps réel. Les développeurs peuvent utiliser DefaultAzureCredential ou une clé API pour l'authentification, et configurer facilement l'environnement avec des variables d'environnement.

Compatible avec~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

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Azure.AI.VoiceLive (.NET)

SDK vocal en temps réel pour l'IA Azure, conçu pour créer des assistants vocaux bidirectionnels avec Azure AI.

Installation

dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio                    # Pour la capture/lecture audio

Versions actuelles : Stable v1.0.0, Preview v1.1.0-beta.1

Variables d'environnement

AZURE_VOICELIVE_ENDPOINT=https://<ressource>.services.ai.azure.com/  # Obligatoire : point de terminaison Voice Live
AZURE_VOICELIVE_MODEL=gpt-4o-realtime-preview  # Obligatoire : nom du déploiement du modèle
AZURE_VOICELIVE_VOICE=en-US-AvaNeural  # Facultatif : nom de la voix Voice Live
AZURE_VOICELIVE_API_KEY=<votre-clé-api>  # Obligatoire uniquement pour l'authentification AzureKeyCredential
AZURE_TOKEN_CREDENTIALS=prod  # Obligatoire uniquement si DefaultAzureCredential est utilisé en production

Authentification

Jeton d'accès Microsoft Entra

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

Uri endpoint = new Uri("https://votre-ressource.cognitiveservices.azure.com");
// Développement local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credential_spécifique>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou utiliser un identifiant spécifique directement en production :
// Voir 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);

Rôle requis : Cognitive Services User (attribuer dans le Portail Azure → Contrôle d'accès)

Clé API

Uri endpoint = new Uri("https://votre-ressource.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("votre-clé-api");
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);

Hiérarchie du client

VoiceLiveClient
└── VoiceLiveSession (connexion WebSocket)
    ├── ConfigureSessionAsync()
    ├── GetUpdatesAsync() → événements SessionUpdate
    ├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
    ├── SendAudioAsync()
    └── StartResponseAsync()

Workflow principal

1. Démarrer une session et configurer

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";

// Démarrer la session
using VoiceLiveSession session = await client.StartSessionAsync(model);

// Configurer la session
VoiceLiveSessionOptions sessionOptions = new()
{
    Model = model,
    Instructions = "Vous êtes un assistant IA utile. Répondez naturellement.",
    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
};

// Définir les modalités (texte et audio pour les assistants vocaux)
sessionOptions.Modalities.Clear();
sessionOptions.Modalities.Add(InteractionModality.Text);
sessionOptions.Modalities.Add(InteractionModality.Audio);

await session.ConfigureSessionAsync(sessionOptions);

2. Traiter les événements

await foreach (SessionUpdate serverEvent in session.GetUpdatesAsync())
{
    switch (serverEvent)
    {
        case SessionUpdateResponseAudioDelta audioDelta:
            byte[] audioData = audioDelta.Delta.ToArray();
            // Lire l'audio via NAudio ou une autre bibliothèque audio
            break;
            
        case SessionUpdateResponseTextDelta textDelta:
            Console.Write(textDelta.Delta);
            break;
            
        case SessionUpdateResponseFunctionCallArgumentsDone functionCall:
            // Gérer l'appel de fonction (voir la section Appel de fonction)
            break;
            
        case SessionUpdateError error:
            Console.WriteLine($"Erreur : {error.Error.Message}");
            break;
            
        case SessionUpdateResponseDone:
            Console.WriteLine("\n--- Réponse terminée ---");
            break;
    }
}

3. Envoyer un message utilisateur

await session.AddItemAsync(new UserMessageItem("Bonjour, pouvez-vous m'aider ?"));
await session.StartResponseAsync();

4. Appel de fonction

// Définir une fonction
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
    Description = "Obtenir la météo actuelle pour un emplacement donné",
    Parameters = BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "La ville et l'État ou le pays"
                }
            },
            "required": ["location"]
        }
        """)
};

// Ajouter aux options de session
sessionOptions.Tools.Add(weatherFunction);

// Gérer l'appel de fonction dans la boucle d'événements
if (serverEvent is SessionUpdateResponseFunctionCallArgumentsDone functionCall)
{
    if (functionCall.Name == "get_current_weather")
    {
        var parameters = JsonSerializer.Deserialize<Dictionary<string, string>>(functionCall.Arguments);
        string location = parameters?["location"] ?? "";
        
        // Appeler un service externe
        string weatherInfo = $"Le temps à {location} est ensoleillé, 24°C.";
        
        // Envoyer la réponse
        await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
        await session.StartResponseAsync();
    }
}

Options de voix

Type de voixClasseExemple
Azure StandardAzureStandardVoice"en-US-AvaNeural"
Azure HDAzureStandardVoice"en-US-Ava:DragonHDLatestNeural"
Azure CustomAzureCustomVoiceVoix personnalisée avec ID de point de terminaison

Modèles pris en charge

ModèleDescription
gpt-4o-realtime-previewGPT-4o avec audio en temps réel
gpt-4o-mini-realtime-previewLéger, interactions rapides
phi4-mm-realtimeMultimodal économique

Référence des types clés

TypeObjectif
VoiceLiveClientClient principal pour créer des sessions
VoiceLiveSessionSession WebSocket active
VoiceLiveSessionOptionsConfiguration de la session
AzureStandardVoiceFournisseur de voix Azure standard
AzureSemanticVadTurnDetectionDétection d'activité vocale
VoiceLiveFunctionDefinitionDéfinition d'outil de fonction
UserMessageItemMessage texte utilisateur
FunctionCallOutputItemRéponse d'appel de fonction
SessionUpdateResponseAudioDeltaÉvénement de bloc audio
SessionUpdateResponseTextDeltaÉvénement de bloc texte

Bonnes pratiques

  1. Toujours définir les deux modalités — Inclure Text et Audio pour les assistants vocaux
  2. Utiliser AzureSemanticVadTurnDetection — Offre un flux de conversation naturel
  3. Configurer une durée de silence appropriée — 500 ms typiquement pour éviter les coupures prématurées
  4. Utiliser l'instruction using — Assure une libération correcte de la session
  5. Gérer tous les types d'événements — Vérifier les erreurs, l'audio, le texte et les appels de fonction
  6. Utiliser DefaultAzureCredential — Ne jamais coder en dur les clés API

Gestion des erreurs

if (serverEvent is SessionUpdateError error)
{
    if (error.Error.Message.Contains("Cancellation failed: no active response"))
    {
        // Erreur bénigne, peut être ignorée
    }
    else
    {
        Console.WriteLine($"Erreur : {error.Error.Message}");
    }
}

Configuration audio

  • Format d'entrée : InputAudioFormat.Pcm16 (PCM 16 bits)
  • Format de sortie : OutputAudioFormat.Pcm16
  • Taux d'échantillonnage : 24 kHz recommandé
  • Canaux : Mono

SDK associés

SDKObjectifInstallation
Azure.AI.VoiceLiveVoix en temps réel (ce SDK)dotnet add package Azure.AI.VoiceLive
Microsoft.CognitiveServices.SpeechSynthèse vocale, reconnaissance vocaledotnet add package Microsoft.CognitiveServices.Speech
NAudioCapture/lecture audiodotnet add package NAudio

Liens de référence

RessourceURL
Paquet NuGethttps://www.nuget.org/packages/Azure.AI.VoiceLive
Référence APIhttps://learn.microsoft.com/dotnet/api/azure.ai.voicelive
Code source GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.VoiceLive
Guide de démarrage rapidehttps://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.

Skills associés