Communitygithub.com

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET。双方向WebSocket通信を使用したリアルタイム音声AIアプリケーションを構築します。音声アシスタント、会話型AI、リアルタイム音声認識・合成、音声対応チャットボットに使用します。トリガー:「音声ライブ」「リアルタイム音声」「VoiceLiveClient」「VoiceLiveSession」「音声アシスタント.NET」「双方向オーディオ」「音声対音声」。

azure-ai-voicelive-dotnet とは?

このスキルは、Azure AI Voice Live .NET SDK(`Azure.AI.VoiceLive` パッケージ)をClaude Code、Cursor、CodexなどのAIエージェント環境で利用するためのものです。開発者は、双方向のWebSocket通信を介して、音声アシスタントやリアルタイム音声対音声アプリケーションを迅速に構築できます。SDKは、`VoiceLiveClient`と`VoiceLiveSession`によるクライアント階層モデルを提供し、セッションの設定、イベントの処理(音声デルタ、テキストデルタ、関数呼び出しなど)、ユーザーメッセージの送信、音声入出力をサポートします。認証はMicrosoft Entraトークン資格情報またはAPIキーに対応し、`gpt-4o-realtime-preview`などのモデルを利用可能です。セマンティックVADによるターン検出や関数呼び出し機能も備えており、自然な会話フローを実現します。

対応~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 ユーザー (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.

関連スキル