Azure.AI.VoiceLive (.NET)
SDK de voz em tempo real para IA da Azure, voltado para a construção de assistentes de voz bidirecionais.
Instalação
dotnet add package Azure.AI.VoiceLive
dotnet add package Azure.Identity
dotnet add package NAudio
Versões Atuais: Estável v1.0.0, Prévia v1.1.0-beta.1
Variáveis de Ambiente
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=<sua-chave-api>
AZURE_TOKEN_CREDENTIALS=prod
Autenticação
Credencial de Token do Microsoft Entra
using Azure.Identity;
using Azure.AI.VoiceLive;
Uri endpoint = new Uri("https://seu-recurso.cognitiveservices.azure.com");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);
Função Necessária: Usuário dos Serviços Cognitivos (atribua no Portal do Azure → Controle de acesso)
Chave de API
Uri endpoint = new Uri("https://seu-recurso.cognitiveservices.azure.com");
AzureKeyCredential credential = new AzureKeyCredential("sua-chave-api");
VoiceLiveClient client = new VoiceLiveClient(endpoint, credential);
Hierarquia do Cliente
VoiceLiveClient
└── VoiceLiveSession (conexão WebSocket)
├── ConfigureSessionAsync()
├── GetUpdatesAsync() → eventos SessionUpdate
├── AddItemAsync() → UserMessageItem, FunctionCallOutputItem
├── SendAudioAsync()
└── StartResponseAsync()
Fluxo de Trabalho Principal
1. Iniciar Sessão e 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 = "Você é um assistente de IA útil. Responda naturalmente.",
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. Processar 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($"Erro: {error.Error.Message}");
break;
case SessionUpdateResponseDone:
Console.WriteLine("\n--- Resposta completa ---");
break;
}
}
3. Enviar Mensagem do Usuário
await session.AddItemAsync(new UserMessageItem("Olá, você pode me ajudar?"));
await session.StartResponseAsync();
4. Chamada de Funções
var weatherFunction = new VoiceLiveFunctionDefinition("get_current_weather")
{
Description = "Obter o clima atual para um determinado local",
Parameters = BinaryData.FromString("""
{
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "A cidade e estado ou 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 = $"O clima em {location} está ensolarado, 75°F.";
await session.AddItemAsync(new FunctionCallOutputItem(functionCall.CallId, weatherInfo));
await session.StartResponseAsync();
}
}
Opções de Voz
| Tipo de Voz | Classe | Exemplo |
|---|
| Azure Standard | AzureStandardVoice | "en-US-AvaNeural" |
| Azure HD | AzureStandardVoice | "en-US-Ava:DragonHDLatestNeural" |
| Azure Custom | AzureCustomVoice | Voz personalizada com ID de endpoint |
Modelos Suportados
| Modelo | Descrição |
|---|
gpt-4o-realtime-preview | GPT-4o com áudio em tempo real |
gpt-4o-mini-realtime-preview | Interações leves e rápidas |
phi4-mm-realtime | Multimodal com bom custo-benefício |
Referência de Tipos Principais
| Tipo | Propósito |
|---|
VoiceLiveClient | Cliente principal para criar sessões |
VoiceLiveSession | Sessão WebSocket ativa |
VoiceLiveSessionOptions | Configuração da sessão |
AzureStandardVoice | Provedor de voz padrão da Azure |
AzureSemanticVadTurnDetection | Detecção de atividade de voz |
VoiceLiveFunctionDefinition | Definição de ferramenta de função |
UserMessageItem | Mensagem de texto do usuário |
FunctionCallOutputItem | Resposta de chamada de função |
SessionUpdateResponseAudioDelta | Evento de bloco de áudio |
SessionUpdateResponseTextDelta | Evento de bloco de texto |
Melhores Práticas
- Sempre defina ambas as modalidades — Inclua
Text e Audio para assistentes de voz
- Use
AzureSemanticVadTurnDetection — Proporciona fluxo de conversação natural
- Configure uma duração de silêncio adequada — 500ms é típico para evitar cortes prematuros
- Use a instrução
using — Garante o descarte adequado da sessão
- Trate todos os tipos de eventos — Verifique erros, áudio, texto e chamadas de função
- Use DefaultAzureCredential — Nunca codifique chaves de API
Tratamento de Erros
if (serverEvent is SessionUpdateError error)
{
if (error.Error.Message.Contains("Cancellation failed: no active response"))
{
}
else
{
Console.WriteLine($"Erro: {error.Error.Message}");
}
}
Configuração de Áudio
- Formato de Entrada:
InputAudioFormat.Pcm16 (PCM de 16 bits)
- Formato de Saída:
OutputAudioFormat.Pcm16
- Taxa de Amostragem: 24kHz recomendada
- Canais: Mono
SDKs Relacionados
| SDK | Propósito | Instalação |
|---|
Azure.AI.VoiceLive | Voz em tempo real (este SDK) | dotnet add package Azure.AI.VoiceLive |
Microsoft.CognitiveServices.Speech | Fala para texto, texto para fala | dotnet add package Microsoft.CognitiveServices.Speech |
NAudio | Captura/reprodução de áudio | dotnet add package NAudio |
Links de Referência