Communitygithub.com

microsoft/azure-ai-voicelive-dotnet

适用于 .NET 的 Azure AI Voice Live SDK。构建具有双向 WebSocket 通信的实时语音 AI 应用程序,用于语音助手、对话式 AI、实时语音到语音以及支持语音的聊天机器人。

azure-ai-voicelive-dotnet 是什么?

Azure.AI.VoiceLive (.NET) 是微软提供的一个实时语音 AI SDK,专为 .NET 开发者设计,用于构建具备双向 WebSocket 通信的语音助手和对话式 AI 应用。该 SDK 支持多种认证方式,包括 Microsoft Entra 令牌凭证和 API 密钥,并提供了从会话启动、配置、事件处理到函数调用的完整工作流。它支持 GPT-4o 实时预览、GPT-4o-mini 实时预览以及 phi4-mm-realtime 等模型,并提供了标准语音和自定义语音选项。开发者可以通过 NuGet 包快速集成,并利用 NAudio 进行音频捕获和播放。该 SDK 适用于实时语音转语音、语音聊天机器人、语音助手等场景,具有详细的事件类型和最佳实践指南,确保高效稳定的实时语音交互。

兼容平台~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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Azure.AI.VoiceLive (.NET)

用于构建支持双向语音助手的实时语音 AI SDK,基于 Azure AI。

安装

dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio                    # 用于音频捕获/播放

当前版本:稳定版 v1.0.0,预览版 v1.1.0-beta.1

环境变量

AZURE_VOICELIVE_ENDPOINT=https://<resource>.services.ai.azure.com/  # 必需:Voice Live 端点
AZURE_VOICELIVE_MODEL=gpt-4o-realtime-preview  # 必需:模型部署名称
AZURE_VOICELIVE_VOICE=en-US-AvaNeural  # 可选:Voice Live 语音名称
AZURE_VOICELIVE_API_KEY=<your-api-key>  # 仅在使用 AzureKeyCredential 认证时需要
AZURE_TOKEN_CREDENTIALS=prod  # 仅在生产环境中使用 DefaultAzureCredential 时需要

认证

Microsoft Entra 令牌凭证

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

Uri endpoint = new Uri("https://your-resource.cognitiveservices.azure.com");
// 本地开发:DefaultAzureCredential。生产环境:设置 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<特定凭证>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 或直接在 production 中使用特定凭证:
// 请参阅 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);

必需角色:Cognitive Services User(在 Azure 门户 → 访问控制中分配)

API 密钥

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

客户端层次结构

VoiceLiveClient
└── VoiceLiveSession (WebSocket 连接)
    ├── ConfigureSessionAsync()
    ├── GetUpdatesAsync() → SessionUpdate 事件
    ├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
    ├── SendAudioAsync()
    └── StartResponseAsync()

核心工作流

1. 启动会话并进行配置

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

// 启动会话
using VoiceLiveSession session = await client.StartSessionAsync(model);

// 配置会话
VoiceLiveSessionOptions sessionOptions = new()
{
    Model = model,
    Instructions = "你是一个有用的 AI 助手。请自然回答。",
    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
};

// 设置模态(语音助手需要同时包含文本和音频)
sessionOptions.Modalities.Clear();
sessionOptions.Modalities.Add(InteractionModality.Text);
sessionOptions.Modalities.Add(InteractionModality.Audio);

await session.ConfigureSessionAsync(sessionOptions);

2. 处理事件

await foreach (SessionUpdate serverEvent in session.GetUpdatesAsync())
{
    switch (serverEvent)
    {
        case SessionUpdateResponseAudioDelta audioDelta:
            byte[] audioData = audioDelta.Delta.ToArray();
            // 通过 NAudio 或其他音频库播放音频
            break;
            
        case SessionUpdateResponseTextDelta textDelta:
            Console.Write(textDelta.Delta);
            break;
            
        case SessionUpdateResponseFunctionCallArgumentsDone functionCall:
            // 处理函数调用(请参阅函数调用部分)
            break;
            
        case SessionUpdateError error:
            Console.WriteLine($"错误:{error.Error.Message}");
            break;
            
        case SessionUpdateResponseDone:
            Console.WriteLine("\n--- 响应完成 ---");
            break;
    }
}

3. 发送用户消息

await session.AddItemAsync(new UserMessageItem("你好,你能帮我吗?"));
await session.StartResponseAsync();

4. 函数调用

// 定义函数
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
    Description = "获取指定位置的当前天气",
    Parameters = BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "城市和州或国家"
                }
            },
            "required": ["location"]
        }
        """)
};

// 添加到会话选项
sessionOptions.Tools.Add(weatherFunction);

// 在事件循环中处理函数调用
if (serverEvent is SessionUpdateResponseFunctionCallArgumentsDone functionCall)
{
    if (functionCall.Name == "get_current_weather")
    {
        var parameters = JsonSerializer.Deserialize<Dictionary<string, string>>(functionCall.Arguments);
        string location = parameters?["location"] ?? "";
        
        // 调用外部服务
        string weatherInfo = $"{location} 的天气是晴天,75°F。";
        
        // 发送响应
        await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
        await session.StartResponseAsync();
    }
}

语音选项

语音类型类示例
Azure 标准AzureStandardVoice"en-US-AvaNeural"
Azure HDAzureStandardVoice"en-US-Ava:DragonHDLatestNeural"
Azure 自定义AzureCustomVoice带端点 ID 的自定义语音

支持的模型

模型描述
gpt-4o-realtime-previewGPT-4o 实时音频
gpt-4o-mini-realtime-preview轻量级,快速交互
phi4-mm-realtime高性价比多模态

关键类型参考

类型用途
VoiceLiveClient用于创建会话的主客户端
VoiceLiveSession活跃的 WebSocket 会话
VoiceLiveSessionOptions会话配置
AzureStandardVoice标准 Azure 语音提供程序
AzureSemanticVadTurnDetection语音活动检测
VoiceLiveFunctionDefinition函数工具定义
UserMessageItem用户文本消息
FunctionCallOutputItem函数调用响应
SessionUpdateResponseAudioDelta音频块事件
SessionUpdateResponseTextDelta文本块事件

最佳实践

  1. 始终设置两种模态 —— 语音助手需包含 Text 和 Audio
  2. 使用 AzureSemanticVadTurnDetection —— 提供自然的对话流程
  3. 配置合适的静默持续时间 —— 通常为 500ms,以避免过早中断
  4. 使用 using 语句 —— 确保正确释放会话资源
  5. 处理所有事件类型 —— 检查错误、音频、文本和函数调用
  6. 使用 DefaultAzureCredential —— 切勿硬编码 API 密钥

错误处理

if (serverEvent is SessionUpdateError error)
{
    if (error.Error.Message.Contains("Cancellation failed: no active response"))
    {
        // 良性错误,可忽略
    }
    else
    {
        Console.WriteLine($"错误:{error.Error.Message}");
    }
}

音频配置

  • 输入格式:InputAudioFormat.Pcm16(16 位 PCM)
  • 输出格式:OutputAudioFormat.Pcm16
  • 采样率:推荐 24kHz
  • 声道:单声道

相关 SDK

SDK用途安装命令
Azure.AI.VoiceLive实时语音(本 SDK)dotnet add package Azure.AI.VoiceLive
Microsoft.CognitiveServices.Speech语音转文本、文本转语音dotnet add package Microsoft.CognitiveServices.Speech
NAudio音频捕获/播放dotnet add package NAudio

参考链接

资源URL
NuGet 包https://www.nuget.org/packages/Azure.AI.VoiceLive
API 参考https://learn.microsoft.com/dotnet/api/azure.ai.voicelive
GitHub 源码https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.VoiceLive
快速入门https://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.

相关技能