mcpField
A
azure-ai-voicelive-dotnet

azure-ai-voicelive-dotnet

github.com/sickn33開発48.7k67 回インストール今日更新
リポジトリ

azure-ai-voicelive-dotnet について

Azure.AI.VoiceLive (.NET)は、Azure AIを使ったリアルタイム双方向音声アシスタントを構築するSDKです。.NET開発者向けに、WebSocketセッション、音声・テキストイベントのストリーミング、関数呼び出しを提供します。

主な機能

  1. 01WebSocket音声セッションの作成
  2. 02音声送信とイベントのストリーミング受信
  3. 03音声とセッションオプションの設定
  4. 04テキストと音声応答の処理
  5. 05関数呼び出しの定義

活用シーン

  1. 01リアルタイム音声アシスタントの構築
  2. 02.NETアプリでの音声インタラクション配信
  3. 03音声セッションへの関数呼び出しの追加

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-ai-voicelive-dotnet

インストール後、Claude Code で/azure-ai-voicelive-dotnetを入力して読み込まれたか確認します。

詳細

Azure.AI.VoiceLive(.NET)

Azure AI を使用して双方向の音声アシスタントを構築するためのリアルタイム音声 AI SDK です。

インストール

dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio                    # For audio capture/playback

バージョンの範囲:例は SDK の断片です。これらの例を最新バージョンの一覧として扱うのではなく、互換性のあるパッケージを指定し、リンク先の Microsoft ドキュメントで API とモデルの利用可能状況を確認してください。

環境変数

AZURE_VOICELIVE_ENDPOINT=https://<resource>.services.ai.azure.com/
AZURE_VOICELIVE_MODEL=gpt-4o-realtime-preview
AZURE_VOICELIVE_VOICE=en-US-AvaNeural
# Optional: API key if not using Entra ID
AZURE_VOICELIVE_API_KEY=<your-api-key>

認証

Microsoft Entra ID(推奨)
using Azure.Identity;
using Azure.AI.VoiceLive;

Uri endpoint = new Uri("https://your-resource.cognitiveservices.azure.com");
DefaultAzureCredential credential = new DefaultAzureCredential();
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 connection)
    ├── ConfigureSessionAsync()
    ├── GetUpdatesAsync() → SessionUpdate events
    ├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
    ├── SendAudioAsync()
    └── StartResponseAsync()

音声とツールの境界

該当するマイクの使用・録音・送信について同意を得て、承認済みの Azure リソース/リージョンを選択し、セッションの継続時間とコストに上限を設けてください。モデルが提供するツールの引数は信頼できないものとして扱います。スキーマを検証し、操作を許可リストに登録し、外部に影響する処理には認可を必須にしてください。シークレットを指示やログに含めないでください。また、関数定義を実行済みの連携として扱わないでください。ツールを追加した後はセッションを再構成してください。正確な音声形式とサンプルレートは、指定したモデルと SDK によって異なります。

基本的なワークフロー

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

// Start session
using VoiceLiveSession session = await client.StartSessionAsync(model);

// Configure session
VoiceLiveSessionOptions sessionOptions = new()
{
    Model = model,
    Instructions = "You are a helpful AI assistant. Respond naturally.",
    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
};

// Set modalities (both text and audio for voice assistants)
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();
            // Play audio via NAudio or other audio library
            break;
            
        case SessionUpdateResponseTextDelta textDelta:
            Console.Write(textDelta.Delta);
            break;
            
        case SessionUpdateResponseFunctionCallArgumentsDone functionCall:
            // Handle function call (see Function Calling section)
            break;
            
        case SessionUpdateError error:
            Console.WriteLine($"Error: {error.Error.Message}");
            break;
            
        case SessionUpdateResponseDone:
            Console.WriteLine("\n--- Response complete ---");
            break;
    }
}
3. ユーザーメッセージを送信する
await session.AddItemAsync(new UserMessageItem("Hello, can you help me?"));
await session.StartResponseAsync();
4. 関数呼び出し
// Define function
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
    Description = "Get the current weather for a given location",
    Parameters = BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state or country"
                }
            },
            "required": ["location"]
        }
        """)
};

// Add to session options
sessionOptions.Tools.Add(weatherFunction);

// Handle function call in event loop
if (serverEvent is SessionUpdateResponseFunctionCallArgumentsDone functionCall)
{
    if (functionCall.Name == "get_current_weather")
    {
        var parameters = JsonSerializer.Deserialize<Dictionary<string, string>>(functionCall.Arguments);
        if (parameters is null || !parameters.TryGetValue("location", out string? location)
            || string.IsNullOrWhiteSpace(location))
            throw new ArgumentException("location is required");
        
        // Call external service
        string weatherInfo = $"Demo only: no live weather lookup was performed for {location}.";
        
        // Send response
        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セッションの構成
AzureStandardVoiceAzure 標準音声プロバイダー
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"))
    {
        // Benign error, can ignore
    }
    else
    {
        Console.WriteLine($"Error: {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

使用する場面

このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。

制限事項

  • このスキルは、タスクが上記のスコープに明確に一致する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、専門家によるレビューの代替として扱わないでください。
  • 必要な入力、権限、安全境界、成功基準が欠けている場合は、作業を中断して確認を求めてください。

コメント