Azure.AI.VoiceLive (.NET)
SDK vocal en temps réel pour l'IA Azure, conçu pour créer des assistants vocaux bidirectionnels avec Azure AI.
Installation
dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio
Versions actuelles : Stable v1.0.0, Preview v1.1.0-beta.1
Variables d'environnement
AZURE_VOICELIVE_ENDPOINT=https://<ressource>.services.ai.azure.com/
AZURE_VOICELIVE_MODEL=gpt-4o-realtime-preview
AZURE_VOICELIVE_VOICE=en-US-AvaNeural
AZURE_VOICELIVE_API_KEY=<votre-clé-api>
AZURE_TOKEN_CREDENTIALS=prod
Authentification
Jeton d'accès Microsoft Entra
using Azure.Identity;
using Azure.AI.VoiceLive;
Uri endpoint = new Uri("https://votre-ressource.cognitiveservices.azure.com");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);
Rôle requis : Cognitive Services User (attribuer dans le Portail Azure → Contrôle d'accès)
Clé API
Uri endpoint = new Uri("https://votre-ressource.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("votre-clé-api");
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);
Hiérarchie du client
VoiceLiveClient
└── VoiceLiveSession (connexion WebSocket)
├── ConfigureSessionAsync()
├── GetUpdatesAsync() → événements SessionUpdate
├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
├── SendAudioAsync()
└── StartResponseAsync()
Workflow principal
1. Démarrer une session et configurer
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 = "Vous êtes un assistant IA utile. Répondez naturellement.",
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. Traiter les événements
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($"Erreur : {error.Error.Message}");
break;
case SessionUpdateResponseDone:
Console.WriteLine("\n--- Réponse terminée ---");
break;
}
}
3. Envoyer un message utilisateur
await session.AddItemAsync(new UserMessageItem("Bonjour, pouvez-vous m'aider ?"));
await session.StartResponseAsync();
4. Appel de fonction
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
Description = "Obtenir la météo actuelle pour un emplacement donné",
Parameters = BinaryData.FromString("""
{
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "La ville et l'État ou le pays"
}
},
"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 = $"Le temps à {location} est ensoleillé, 24°C.";
await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
await session.StartResponseAsync();
}
}
Options de voix
| Type de voix | Classe | Exemple |
|---|
| Azure Standard | AzureStandardVoice | "en-US-AvaNeural" |
| Azure HD | AzureStandardVoice | "en-US-Ava:DragonHDLatestNeural" |
| Azure Custom | AzureCustomVoice | Voix personnalisée avec ID de point de terminaison |
Modèles pris en charge
| Modèle | Description |
|---|
gpt-4o-realtime-preview | GPT-4o avec audio en temps réel |
gpt-4o-mini-realtime-preview | Léger, interactions rapides |
phi4-mm-realtime | Multimodal économique |
Référence des types clés
| Type | Objectif |
|---|
VoiceLiveClient | Client principal pour créer des sessions |
VoiceLiveSession | Session WebSocket active |
VoiceLiveSessionOptions | Configuration de la session |
AzureStandardVoice | Fournisseur de voix Azure standard |
AzureSemanticVadTurnDetection | Détection d'activité vocale |
VoiceLiveFunctionDefinition | Définition d'outil de fonction |
UserMessageItem | Message texte utilisateur |
FunctionCallOutputItem | Réponse d'appel de fonction |
SessionUpdateResponseAudioDelta | Événement de bloc audio |
SessionUpdateResponseTextDelta | Événement de bloc texte |
Bonnes pratiques
- Toujours définir les deux modalités — Inclure
Text et Audio pour les assistants vocaux
- Utiliser
AzureSemanticVadTurnDetection — Offre un flux de conversation naturel
- Configurer une durée de silence appropriée — 500 ms typiquement pour éviter les coupures prématurées
- Utiliser l'instruction
using — Assure une libération correcte de la session
- Gérer tous les types d'événements — Vérifier les erreurs, l'audio, le texte et les appels de fonction
- Utiliser DefaultAzureCredential — Ne jamais coder en dur les clés API
Gestion des erreurs
if (serverEvent is SessionUpdateError error)
{
if (error.Error.Message.Contains("Cancellation failed: no active response"))
{
}
else
{
Console.WriteLine($"Erreur : {error.Error.Message}");
}
}
Configuration audio
- Format d'entrée :
InputAudioFormat.Pcm16 (PCM 16 bits)
- Format de sortie :
OutputAudioFormat.Pcm16
- Taux d'échantillonnage : 24 kHz recommandé
- Canaux : Mono
SDK associés
| SDK | Objectif | Installation |
|---|
Azure.AI.VoiceLive | Voix en temps réel (ce SDK) | dotnet add package Azure.AI.VoiceLive |
Microsoft.CognitiveServices.Speech | Synthèse vocale, reconnaissance vocale | dotnet add package Microsoft.CognitiveServices.Speech |
NAudio | Capture/lecture audio | dotnet add package NAudio |
Liens de référence