Azure AI 语音实时通信 .NET SDK
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/
AZURE_VOICELIVE_MODEL=gpt-4o-realtime-preview
AZURE_VOICELIVE_VOICE=en-US-AvaNeural
可选:如果不使用 Entra ID,请提供 API 密钥
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 门户 → 访问控制中分配)
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 = "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
};
// 设置模态(语音助手需同时包含文本和音频)
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 Sess### 3. 发送用户消息### 4. 函数调用 (Function Calling)// 添加到会话选项
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 HD | 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 | 会话配置 |
| AzureStandardVoice | 标准 Azure 语音提供者 |
| AzureSemanticVadTurnDetection | 语音活动检测 (VAD) |
| 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.Error.Message}");
}
}音频配置
- 输入格式:
InputAudioFormat.Pcm16(16位 PCM)
- 输出格式:
OutputAudioFormat.Pcm16
- 采样率:建议 24kHz
- 声道:单声道 (Mono)
相关 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 |
使用场景
本技能适用于执行概览中所描述的工作流或操作。局限性
- 仅在任务明确符合上述范围时使用此技能。
- 不要将输出结果视为针对特定环境的验证、测试或专家评审的替代方案。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停止操作并请求澄清。