Azure.AI.VoiceLive (.NET)
Echtzeit-Sprach-KI SDK für die Entwicklung bidirektionaler Sprachassistenten mit Azure KI.
Installation
dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio
Aktuelle Versionen: Stabil v1.0.0, Vorschau v1.1.0-beta.1
Umgebungsvariablen
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
Authentifizierung
Microsoft Entra Token-Anmeldeinformationen
using Azure.Identity;
using Azure.AI.VoiceLive;
Uri endpoint = new Uri("https://ihre-resource.cognitiveservices.azure.com");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);
Erforderliche Rolle: Cognitive Services User (im Azure-Portal → Zugriffssteuerung zuweisen)
API-Schlüssel
Uri endpoint = new Uri("https://ihre-resource.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("ihr-api-key");
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);
Client-Hierarchie
VoiceLiveClient
└── VoiceLiveSession (WebSocket-Verbindung)
├── ConfigureSessionAsync()
├── GetUpdatesAsync() → SessionUpdate-Ereignisse
├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
├── SendAudioAsync()
└── StartResponseAsync()
Kern-Workflow
1. Sitzung starten und konfigurieren
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 = "Sie sind ein hilfreicher KI-Assistent. Antworten Sie natürlich.",
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. Ereignisse verarbeiten
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($"Fehler: {error.Error.Message}");
break;
case SessionUpdateResponseDone:
Console.WriteLine("\n--- Antwort abgeschlossen ---");
break;
}
}
3. Benutzernachricht senden
await session.AddItemAsync(new UserMessageItem("Hallo, können Sie mir helfen?"));
await session.StartResponseAsync();
4. Funktionen aufrufen (Function Calling)
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
Description = "Ruft das aktuelle Wetter für einen bestimmten Ort ab",
Parameters = BinaryData.FromString("""
{
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Die Stadt und das Bundesland oder Land"
}
},
"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 = $"Das Wetter in {location} ist sonnig, 24°C.";
await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
await session.StartResponseAsync();
}
}
Sprachoptionen
| Sprachtyp | Klasse | Beispiel |
|---|
| Azure Standard | AzureStandardVoice | "en-US-AvaNeural" |
| Azure HD | AzureStandardVoice | "en-US-Ava:DragonHDLatestNeural" |
| Azure Custom | AzureCustomVoice | Benutzerdefinierte Stimme mit Endpunkt-ID |
Unterstützte Modelle
| Modell | Beschreibung |
|---|
gpt-4o-realtime-preview | GPT-4o mit Echtzeit-Audio |
gpt-4o-mini-realtime-preview | Leichtgewichtig, schnelle Interaktionen |
phi4-mm-realtime | Kosteneffizient multimodal |
Referenz wichtiger Typen
| Typ | Zweck |
|---|
VoiceLiveClient | Hauptclient zum Erstellen von Sitzungen |
VoiceLiveSession | Aktive WebSocket-Sitzung |
VoiceLiveSessionOptions | Sitzungskonfiguration |
AzureStandardVoice | Standard-Azure-Sprachprovider |
AzureSemanticVadTurnDetection | Spracherkennung |
VoiceLiveFunctionDefinition | Funktionswerkzeug-Definition |
UserMessageItem | Benutzertextnachricht |
FunctionCallOutputItem | Funktionsaufruf-Antwort |
SessionUpdateResponseAudioDelta | Audio-Chunk-Ereignis |
SessionUpdateResponseTextDelta | Text-Chunk-Ereignis |
Best Practices
- Immer beide Modalitäten setzen — Fügen Sie
Text und Audio für Sprachassistenten hinzu
AzureSemanticVadTurnDetection verwenden — Ermöglicht natürlichen Gesprächsfluss
- Angemessene Stille-Dauer konfigurieren — typischerweise 500ms, um vorzeitige Abbrüche zu vermeiden
using-Anweisung verwenden — Stellt ordnungsgemäße Sitzungsfreigabe sicher
- Alle Ereignistypen behandeln — Überprüfen Sie auf Fehler, Audio, Text und Funktionsaufrufe
DefaultAzureCredential verwenden — Niemals API-Schlüssel hartcodieren
Fehlerbehandlung
if (serverEvent is SessionUpdateError error)
{
if (error.Error.Message.Contains("Cancellation failed: no active response"))
{
}
else
{
Console.WriteLine($"Fehler: {error.Error.Message}");
}
}
Audio-Konfiguration
- Eingabeformat:
InputAudioFormat.Pcm16 (16-Bit PCM)
- Ausgabeformat:
OutputAudioFormat.Pcm16
- Abtastrate: 24 kHz empfohlen
- Kanäle: Mono
Verwandte SDKs
| SDK | Zweck | Installation |
|---|
Azure.AI.VoiceLive | Echtzeit-Sprache (dieses SDK) | dotnet add package Azure.AI.VoiceLive |
Microsoft.CognitiveServices.Speech | Sprache-zu-Text, Text-zu-Sprache | dotnet add package Microsoft.CognitiveServices.Speech |
NAudio | Audio-Aufnahme/Wiedergabe | dotnet add package NAudio |
Referenzlinks