Communitygithub.com

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET。透過雙向 WebSocket 通訊,建構即時語音 AI 應用程式,適用於語音助手、對話式 AI、即時語音轉語音及語音聊天機器人。

azure-ai-voicelive-dotnet 是什麼?

此技能為 .NET 開發者提供 Azure.AI.VoiceLive SDK 的完整使用指南。此 SDK 支援使用 GPT-4o 等模型建立即時、雙向的語音助理,並透過 WebSocket 連接處理音訊串流、文字事件與函式呼叫。文件詳細說明安裝步驟、環境變數設定、支援多種驗證方式(如 Microsoft Entra Token 與 API Key),並展示從工作階段配置、事件處理到音訊播放的完整工作流程。此外,也涵蓋語音選項(標準、HD、自訂)、支援模型清單、功能呼叫實作、錯誤處理及最佳實務(例如同時啟用文字與音訊模態),協助開發者快速建置穩定且自然的語音互動應用。支援平台為 .NET。

相容平台~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
);
// 或在生產環境中直接使用特定憑證:
// 請參閱 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 入口網站 → 存取控制 (IAM) 中指派)

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}的天氣晴朗,攝氏24度。";
        
        // 傳送回覆
        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-preview具即時音訊功能的 GPT-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.

相關技能