Azure.AI.VoiceLive (.NET)
用于构建支持双向语音助手的实时语音 AI SDK,基于 Azure AI。
安装
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
AZURE_VOICELIVE_API_KEY=<your-api-key>
AZURE_TOKEN_CREDENTIALS=prod
认证
Microsoft Entra 令牌凭证
using Azure.Identity;
using Azure.AI.VoiceLive;
Uri endpoint = new Uri("https://your-resource.cognitiveservices.azure.com");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
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 = "你是一个有用的 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();
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 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 | 语音活动检测 |
VoiceLiveFunctionDefinition | 函数工具定义 |
UserMessageItem | 用户文本消息 |
FunctionCallOutputItem | 函数调用响应 |
SessionUpdateResponseAudioDelta | 音频块事件 |
SessionUpdateResponseTextDelta | 文本块事件 |
最佳实践
- 始终设置两种模态 —— 语音助手需包含
Text 和 Audio
- 使用
AzureSemanticVadTurnDetection —— 提供自然的对话流程
- 配置合适的静默持续时间 —— 通常为 500ms,以避免过早中断
- 使用
using 语句 —— 确保正确释放会话资源
- 处理所有事件类型 —— 检查错误、音频、文本和函数调用
- 使用
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 |
参考链接