Communitygithub.com

microsoft/azure-ai-voicelive-dotnet

SDK do Azure AI Voice Live para .NET. Crie aplicações de voz em tempo real com comunicação bidirecional via WebSocket. Ideal para assistentes de voz, IA conversacional, conversão de fala para fala em tempo real e chatbots ativados por voz. Gatilhos: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

O que é azure-ai-voicelive-dotnet?

O Azure.AI.VoiceLive é um SDK .NET que permite construir aplicações de voz interativas em tempo real com a plataforma Azure AI. Ele utiliza comunicação bidirecional via WebSocket para oferecer suporte a assistentes de voz, chatbots e sistemas de IA conversacional com resposta de áudio e texto em tempo real. O SDK suporta autenticação via Microsoft Entra ID ou chave de API, e oferece funcionalidades como detecção de atividade de voz (VAD), chamada de funções (function calling) e configuração de modelos de linguagem como GPT-4o e Phi-4. É compatível com as plataformas .NET padrão e pode ser integrado com bibliotecas de áudio como NAudio para captura e reprodução. A documentação inclui workflows claros para iniciar uma sessão, configurar opções, processar eventos e lidar com chamadas de função, além de práticas recomendadas para evitar erros comuns.

Funciona com~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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Azure.AI.VoiceLive (.NET)

SDK de voz em tempo real para IA da Azure, voltado para a construção de assistentes de voz bidirecionais.

Instalação

dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio                    # Para captura/reprodução de áudio

Versões Atuais: Estável v1.0.0, Prévia v1.1.0-beta.1

Variáveis de Ambiente

AZURE_VOICELIVE_ENDPOINT=https://<resource>.services.ai.azure.com/  # Obrigatório: endpoint do Voice Live
AZURE_VOICELIVE_MODEL=gpt-4o-realtime-preview  # Obrigatório: nome da implantação do modelo
AZURE_VOICELIVE_VOICE=en-US-AvaNeural  # Opcional: nome da voz do Voice Live
AZURE_VOICELIVE_API_KEY=<sua-chave-api>  # Necessário apenas para autenticação AzureKeyCredential
AZURE_TOKEN_CREDENTIALS=prod  # Necessário apenas se DefaultAzureCredential for usado em produção

Autenticação

Credencial de Token do Microsoft Entra

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

Uri endpoint = new Uri("https://seu-recurso.cognitiveservices.azure.com");
// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credencial_especifica>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou use uma credencial específica diretamente em produção:
// Veja 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);

Função Necessária: Usuário dos Serviços Cognitivos (atribua no Portal do Azure → Controle de acesso)

Chave de API

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

Hierarquia do Cliente

VoiceLiveClient
└── VoiceLiveSession (conexão WebSocket)
    ├── ConfigureSessionAsync()
    ├── GetUpdatesAsync() → eventos SessionUpdate
    ├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
    ├── SendAudioAsync()
    └── StartResponseAsync()

Fluxo de Trabalho Principal

1. Iniciar Sessão e 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 sessão
using VoiceLiveSession session = await client.StartSessionAsync(model);

// Configurar sessão
VoiceLiveSessionOptions sessionOptions = new()
{
    Model = model,
    Instructions = "Você é um assistente de IA útil. Responda naturalmente.",
    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
};

// Definir modalidades (tanto texto quanto áudio para assistentes de voz)
sessionOptions.Modalities.Clear();
sessionOptions.Modalities.Add(InteractionModality.Text);
sessionOptions.Modalities.Add(InteractionModality.Audio);

await session.ConfigureSessionAsync(sessionOptions);

2. Processar Eventos

await foreach (SessionUpdate serverEvent in session.GetUpdatesAsync())
{
    switch (serverEvent)
    {
        case SessionUpdateResponseAudioDelta audioDelta:
            byte[] audioData = audioDelta.Delta.ToArray();
            // Reproduzir áudio via NAudio ou outra biblioteca de áudio
            break;
            
        case SessionUpdateResponseTextDelta textDelta:
            Console.Write(textDelta.Delta);
            break;
            
        case SessionUpdateResponseFunctionCallArgumentsDone functionCall:
            // Tratar chamada de função (veja seção Chamada de Funções)
            break;
            
        case SessionUpdateError error:
            Console.WriteLine($"Erro: {error.Error.Message}");
            break;
            
        case SessionUpdateResponseDone:
            Console.WriteLine("\n--- Resposta completa ---");
            break;
    }
}

3. Enviar Mensagem do Usuário

await session.AddItemAsync(new UserMessageItem("Olá, você pode me ajudar?"));
await session.StartResponseAsync();

4. Chamada de Funções

// Definir função
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
    Description = "Obter o clima atual para um determinado local",
    Parameters = BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "A cidade e estado ou país"
                }
            },
            "required": ["location"]
        }
        """)
};

// Adicionar às opções da sessão
sessionOptions.Tools.Add(weatherFunction);

// Tratar chamada de função no loop 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"] ?? "";
        
        // Chamar serviço externo
        string weatherInfo = $"O clima em {location} está ensolarado, 75°F.";
        
        // Enviar resposta
        await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
        await session.StartResponseAsync();
    }
}

Opções de Voz

Tipo de VozClasseExemplo
Azure StandardAzureStandardVoice"en-US-AvaNeural"
Azure HDAzureStandardVoice"en-US-Ava:DragonHDLatestNeural"
Azure CustomAzureCustomVoiceVoz personalizada com ID de endpoint

Modelos Suportados

ModeloDescrição
gpt-4o-realtime-previewGPT-4o com áudio em tempo real
gpt-4o-mini-realtime-previewInterações leves e rápidas
phi4-mm-realtimeMultimodal com bom custo-benefício

Referência de Tipos Principais

TipoPropósito
VoiceLiveClientCliente principal para criar sessões
VoiceLiveSessionSessão WebSocket ativa
VoiceLiveSessionOptionsConfiguração da sessão
AzureStandardVoiceProvedor de voz padrão da Azure
AzureSemanticVadTurnDetectionDetecção de atividade de voz
VoiceLiveFunctionDefinitionDefinição de ferramenta de função
UserMessageItemMensagem de texto do usuário
FunctionCallOutputItemResposta de chamada de função
SessionUpdateResponseAudioDeltaEvento de bloco de áudio
SessionUpdateResponseTextDeltaEvento de bloco de texto

Melhores Práticas

  1. Sempre defina ambas as modalidades — Inclua Text e Audio para assistentes de voz
  2. Use AzureSemanticVadTurnDetection — Proporciona fluxo de conversação natural
  3. Configure uma duração de silêncio adequada — 500ms é típico para evitar cortes prematuros
  4. Use a instrução using — Garante o descarte adequado da sessão
  5. Trate todos os tipos de eventos — Verifique erros, áudio, texto e chamadas de função
  6. Use DefaultAzureCredential — Nunca codifique chaves de API

Tratamento de Erros

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

Configuração de Áudio

  • Formato de Entrada: InputAudioFormat.Pcm16 (PCM de 16 bits)
  • Formato de Saída: OutputAudioFormat.Pcm16
  • Taxa de Amostragem: 24kHz recomendada
  • Canais: Mono

SDKs Relacionados

SDKPropósitoInstalação
Azure.AI.VoiceLiveVoz em tempo real (este SDK)dotnet add package Azure.AI.VoiceLive
Microsoft.CognitiveServices.SpeechFala para texto, texto para faladotnet add package Microsoft.CognitiveServices.Speech
NAudioCaptura/reprodução de áudiodotnet add package NAudio

Links de Referência

RecursoURL
Pacote NuGethttps://www.nuget.org/packages/Azure.AI.VoiceLive
Referência da APIhttps://learn.microsoft.com/dotnet/api/azure.ai.voicelive
Código Fonte no GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.VoiceLive
Início 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.

Habilidades Relacionadas