Azure.AI.VoiceLive (.NET)
SDK de voz AI en tiempo real para construir asistentes de voz bidireccionales con Azure AI.
Instalación
dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio
Versiones actuales: Estable v1.0.0, Vista previa v1.1.0-beta.1
Variables de Entorno
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=<tu-clave-api>
AZURE_TOKEN_CREDENTIALS=prod
Autenticación
Credencial de Token de Microsoft Entra
using Azure.Identity;
using Azure.AI.VoiceLive;
Uri endpoint = new Uri("https://tu-recurso.cognitiveservices.azure.com");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);
Rol requerido: Cognitive Services User (asignar en Azure Portal → Control de acceso)
Clave API
Uri endpoint = new Uri("https://tu-recurso.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("tu-clave-api");
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);
Jerarquía del Cliente
VoiceLiveClient
└── VoiceLiveSession (conexión WebSocket)
├── ConfigureSessionAsync()
├── GetUpdatesAsync() → eventos SessionUpdate
├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
├── SendAudioAsync()
└── StartResponseAsync()
Flujo de Trabajo Principal
1. Iniciar Sesión y Configurar
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 = "Eres un asistente AI útil. Responde de forma natural.",
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. Procesar Eventos
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.Error.Message}");
break;
case SessionUpdateResponseDone:
Console.WriteLine("\n--- Respuesta completa ---");
break;
}
}
3. Enviar Mensaje de Usuario
await session.AddItemAsync(new UserMessageItem("Hola, ¿puedes ayudarme?"));
await session.StartResponseAsync();
4. Llamada a Funciones
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
Description = "Obtener el clima actual para una ubicación dada",
Parameters = BinaryData.FromString("""
{
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "La ciudad y estado o país"
}
},
"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 = $"El clima en {location} es soleado, 24°C.";
await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
await session.StartResponseAsync();
}
}
Opciones de Voz
| Tipo de Voz | Clase | Ejemplo |
|---|
| Azure Standard | AzureStandardVoice | "en-US-AvaNeural" |
| Azure HD | AzureStandardVoice | "en-US-Ava:DragonHDLatestNeural" |
| Azure Personalizada | AzureCustomVoice | Voz personalizada con ID de punto de conexión |
Modelos Soportados
| Modelo | Descripción |
|---|
gpt-4o-realtime-preview | GPT-4o con audio en tiempo real |
gpt-4o-mini-realtime-preview | Interacciones ligeras y rápidas |
phi4-mm-realtime | Multimodal rentable |
Referencia de Tipos Clave
| Tipo | Propósito |
|---|
VoiceLiveClient | Cliente principal para crear sesiones |
VoiceLiveSession | Sesión activa de WebSocket |
VoiceLiveSessionOptions | Configuración de la sesión |
AzureStandardVoice | Proveedor de voz estándar de Azure |
AzureSemanticVadTurnDetection | Detección de actividad de voz |
VoiceLiveFunctionDefinition | Definición de herramienta de función |
UserMessageItem | Mensaje de texto del usuario |
FunctionCallOutputItem | Respuesta de llamada a función |
SessionUpdateResponseAudioDelta | Evento de fragmento de audio |
SessionUpdateResponseTextDelta | Evento de fragmento de texto |
Mejores Prácticas
- Siempre establecer ambas modalidades — Incluir
Text y Audio para asistentes de voz
- Usar
AzureSemanticVadTurnDetection — Proporciona un flujo de conversación natural
- Configurar una duración de silencio adecuada — 500ms típico para evitar cortes prematuros
- Usar la instrucción
using — Garantiza la eliminación adecuada de la sesión
- Manejar todos los tipos de eventos — Verificar errores, audio, texto y llamadas a funciones
- Usar DefaultAzureCredential — Nunca codificar claves API directamente
Manejo de Errores
if (serverEvent is SessionUpdateError error)
{
if (error.Error.Message.Contains("Cancellation failed: no active response"))
{
}
else
{
Console.WriteLine($"Error: {error.Error.Message}");
}
}
Configuración de Audio
- Formato de entrada:
InputAudioFormat.Pcm16 (PCM de 16 bits)
- Formato de salida:
OutputAudioFormat.Pcm16
- Frecuencia de muestreo: 24kHz recomendada
- Canales: Mono
SDKs Relacionados
| SDK | Propósito | Instalación |
|---|
Azure.AI.VoiceLive | Voz en tiempo real (este SDK) | dotnet add package Azure.AI.VoiceLive |
Microsoft.CognitiveServices.Speech | Voz-a-texto, texto-a-voz | dotnet add package Microsoft.CognitiveServices.Speech |
NAudio | Captura/reproducción de audio | dotnet add package NAudio |
Enlaces de Referencia