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 入口網站 → 存取控制 (IAM) 中指派)
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}的天氣晴朗,攝氏24度。";
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 |
參考連結