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. 01创建 WebSocket 语音会话
  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 高清语音AzureStandardVoice"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

适用场景

此技能适用于执行概述中所述的工作流或操作。

限制

  • 仅当任务明确符合上述范围时,才使用此技能。
  • 不要将输出视为特定环境验证、测试或专家评审的替代品。
  • 如果缺少必需的输入、权限、安全边界或成功标准,请停止并请求澄清。

评论

支持 Markdown