Communitygithub.com

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. 양방향 WebSocket 통신으로 실시간 음성 AI 애플리케이션을 구축합니다. 음성 도우미, 대화형 AI, 실시간 음성-음성, 음성 기반 챗봇에 사용됩니다.

azure-ai-voicelive-dotnet란 무엇인가요?

이 스킬은 .NET 개발자가 Azure AI Voice Live SDK를 사용하여 실시간 양방향 음성 AI 애플리케이션을 구축할 수 있도록 지원합니다. VoiceLiveClient와 VoiceLiveSession을 통해 WebSocket 기반의 지속적인 연결을 제공하며, 사용자 메시지 전송, 오디오 스트리밍, 함수 호출 및 응답 처리를 수행할 수 있습니다. SDK는 Azure OpenAI의 실시간 모델(gpt-4o-realtime-preview, gpt-4o-mini-realtime-preview 등)을 활용하며, Azure AD 인증(DefaultAzureCredential) 또는 API 키 인증을 지원합니다. NAudio와 같은 오디오 라이브러리와 함께 사용하여 오디오 캡처 및 재생을 구현할 수 있으며, AzureSemanticVadTurnDetection을 통해 자연스러운 대화 전환(Turn)을 구성할 수 있습니다. 주요 기능으로는 실시간 오디오/텍스트 델타 이벤트 처리, 함수 호출(Function Calling), 음성 선택(표준/HD/사용자 지정 음성), 오류 처리 등이 포함됩니다.

지원 대상~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에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Azure.AI.VoiceLive (.NET)

Azure AI를 사용하여 양방향 음성 도우미를 구축하기 위한 실시간 음성 AI SDK입니다.

설치

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=<specific_credential> 설정
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 Portal → 액세스 제어에서 할당)

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-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.

관련 스킬