Communitygithub.com

microsoft/azure-ai-voicelive-dotnet

SDK de Azure AI Voice Live para .NET. Crea aplicaciones de voz en tiempo real con comunicación bidireccional mediante WebSocket. Ideal para asistentes de voz, IA conversacional, voz-a-voz en tiempo real y chatbots con capacidad de voz.

¿Qué es azure-ai-voicelive-dotnet?

Azure.AI.VoiceLive es un SDK para .NET que permite construir aplicaciones de voz inteligentes con capacidad de interacción bidireccional en tiempo real utilizando WebSocket. Está diseñado para asistentes de voz, chatbots conversacionales y aplicaciones de voz-a-voz, soportando modelos como GPT-4o en tiempo real y Phi-4 multimodal. Su arquitectura se basa en un cliente principal (`VoiceLiveClient`) que establece sesiones WebSocket (`VoiceLiveSession`), las cuales pueden configurarse con detección de actividad de voz, selección de voz, y manejo de funciones personalizadas. El SDK se integra fácilmente con autenticación mediante Microsoft Entra ID o clave API, y requiere el paquete NAudio para captura/reproducción de audio. Entre sus ventajas destacan la capacidad de procesar eventos de audio, texto y llamadas a funciones en un mismo bucle, y la flexibilidad para elegir entre diferentes voces (estándar, HD o personalizadas). Es útil para desarrolladores que buscan crear experiencias de voz naturales y reactivas, con control fino sobre la detección de turnos y la configuración de la sesión.

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

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Azure.AI.VoiceLive (.NET)

SDK de voz AI en tiempo real para construir asistentes de voz bidireccionales con Azure AI.

Instalación

dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio                    # Para captura/reproducción de audio

Versiones actuales: Estable v1.0.0, Vista previa v1.1.0-beta.1

Variables de Entorno

AZURE_VOICELIVE_ENDPOINT=https://<resource>.services.ai.azure.com/  # Requerido: punto de conexión de Voice Live
AZURE_VOICELIVE_MODEL=gpt-4o-realtime-preview  # Requerido: nombre de implementación del modelo
AZURE_VOICELIVE_VOICE=en-US-AvaNeural  # Opcional: nombre de voz de Voice Live
AZURE_VOICELIVE_API_KEY=<tu-clave-api>  # Solo requerido para autenticación AzureKeyCredential
AZURE_TOKEN_CREDENTIALS=prod  # Requerido solo si se usa DefaultAzureCredential en producción

Autenticación

Credencial de Token de Microsoft Entra

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

Uri endpoint = new Uri("https://tu-recurso.cognitiveservices.azure.com");
// Desarrollo local: DefaultAzureCredential. Producción: establecer AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credential_específico>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// O usar una credencial específica directamente en producción:
// Ver 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);

Rol requerido: Cognitive Services User (asignar en Azure Portal → Control de acceso)

Clave API

Uri endpoint = new Uri("https://tu-recurso.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("tu-clave-api");
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);

Jerarquía del Cliente

VoiceLiveClient
└── VoiceLiveSession (conexión WebSocket)
    ├── ConfigureSessionAsync()
    ├── GetUpdatesAsync() → eventos SessionUpdate
    ├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
    ├── SendAudioAsync()
    └── StartResponseAsync()

Flujo de Trabajo Principal

1. Iniciar Sesión y Configurar

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

// Iniciar sesión
using VoiceLiveSession session = await client.StartSessionAsync(model);

// Configurar sesión
VoiceLiveSessionOptions sessionOptions = new()
{
    Model = model,
    Instructions = "Eres un asistente AI útil. Responde de forma natural.",
    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
};

// Establecer modalidades (tanto texto como audio para asistentes de voz)
sessionOptions.Modalities.Clear();
sessionOptions.Modalities.Add(InteractionModality.Text);
sessionOptions.Modalities.Add(InteractionModality.Audio);

await session.ConfigureSessionAsync(sessionOptions);

2. Procesar Eventos

await foreach (SessionUpdate serverEvent in session.GetUpdatesAsync())
{
    switch (serverEvent)
    {
        case SessionUpdateResponseAudioDelta audioDelta:
            byte[] audioData = audioDelta.Delta.ToArray();
            // Reproducir audio mediante NAudio u otra biblioteca de audio
            break;
            
        case SessionUpdateResponseTextDelta textDelta:
            Console.Write(textDelta.Delta);
            break;
            
        case SessionUpdateResponseFunctionCallArgumentsDone functionCall:
            // Manejar llamada a función (ver sección Llamada a Funciones)
            break;
            
        case SessionUpdateError error:
            Console.WriteLine($"Error: {error.Error.Message}");
            break;
            
        case SessionUpdateResponseDone:
            Console.WriteLine("\n--- Respuesta completa ---");
            break;
    }
}

3. Enviar Mensaje de Usuario

await session.AddItemAsync(new UserMessageItem("Hola, ¿puedes ayudarme?"));
await session.StartResponseAsync();

4. Llamada a Funciones

// Definir función
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
    Description = "Obtener el clima actual para una ubicación dada",
    Parameters = BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "La ciudad y estado o país"
                }
            },
            "required": ["location"]
        }
        """)
};

// Agregar a las opciones de sesión
sessionOptions.Tools.Add(weatherFunction);

// Manejar llamada a función en el bucle de eventos
if (serverEvent is SessionUpdateResponseFunctionCallArgumentsDone functionCall)
{
    if (functionCall.Name == "get_current_weather")
    {
        var parameters = JsonSerializer.Deserialize<Dictionary<string, string>>(functionCall.Arguments);
        string location = parameters?["location"] ?? "";
        
        // Llamar a servicio externo
        string weatherInfo = $"El clima en {location} es soleado, 24°C.";
        
        // Enviar respuesta
        await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
        await session.StartResponseAsync();
    }
}

Opciones de Voz

Tipo de VozClaseEjemplo
Azure StandardAzureStandardVoice"en-US-AvaNeural"
Azure HDAzureStandardVoice"en-US-Ava:DragonHDLatestNeural"
Azure PersonalizadaAzureCustomVoiceVoz personalizada con ID de punto de conexión

Modelos Soportados

ModeloDescripción
gpt-4o-realtime-previewGPT-4o con audio en tiempo real
gpt-4o-mini-realtime-previewInteracciones ligeras y rápidas
phi4-mm-realtimeMultimodal rentable

Referencia de Tipos Clave

TipoPropósito
VoiceLiveClientCliente principal para crear sesiones
VoiceLiveSessionSesión activa de WebSocket
VoiceLiveSessionOptionsConfiguración de la sesión
AzureStandardVoiceProveedor de voz estándar de Azure
AzureSemanticVadTurnDetectionDetección de actividad de voz
VoiceLiveFunctionDefinitionDefinición de herramienta de función
UserMessageItemMensaje de texto del usuario
FunctionCallOutputItemRespuesta de llamada a función
SessionUpdateResponseAudioDeltaEvento de fragmento de audio
SessionUpdateResponseTextDeltaEvento de fragmento de texto

Mejores Prácticas

  1. Siempre establecer ambas modalidades — Incluir Text y Audio para asistentes de voz
  2. Usar AzureSemanticVadTurnDetection — Proporciona un flujo de conversación natural
  3. Configurar una duración de silencio adecuada — 500ms típico para evitar cortes prematuros
  4. Usar la instrucción using — Garantiza la eliminación adecuada de la sesión
  5. Manejar todos los tipos de eventos — Verificar errores, audio, texto y llamadas a funciones
  6. Usar DefaultAzureCredential — Nunca codificar claves API directamente

Manejo de Errores

if (serverEvent is SessionUpdateError error)
{
    if (error.Error.Message.Contains("Cancellation failed: no active response"))
    {
        // Error benigno, se puede ignorar
    }
    else
    {
        Console.WriteLine($"Error: {error.Error.Message}");
    }
}

Configuración de Audio

  • Formato de entrada: InputAudioFormat.Pcm16 (PCM de 16 bits)
  • Formato de salida: OutputAudioFormat.Pcm16
  • Frecuencia de muestreo: 24kHz recomendada
  • Canales: Mono

SDKs Relacionados

SDKPropósitoInstalación
Azure.AI.VoiceLiveVoz en tiempo real (este SDK)dotnet add package Azure.AI.VoiceLive
Microsoft.CognitiveServices.SpeechVoz-a-texto, texto-a-vozdotnet add package Microsoft.CognitiveServices.Speech
NAudioCaptura/reproducción de audiodotnet add package NAudio

Enlaces de Referencia

RecursoURL
Paquete NuGethttps://www.nuget.org/packages/Azure.AI.VoiceLive
Referencia de APIhttps://learn.microsoft.com/dotnet/api/azure.ai.voicelive
Código Fuente en GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.VoiceLive
Inicio Rápidohttps://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 relacionados