opção
LarLar Skill Desenvolvimento de APIs azure-communication-callautomation-java

azure-communication-callautomation-java

microsoft/skills microsoft/skills

Construa fluxos de trabalho de automação de chamadas no lado do servidor com o SDK Java do Azure Communication Services Call Automation, incluindo sistemas IVR, roteamento de chamadas, gravação, reconhecimento DTMF, conversão de texto em fala e fluxos de chamadas com inteligência artificial.

...Expandir tudo
3
Tempo atualizado 19 de Setembro de 2026

Automação de Chamadas do Azure Communication (Java)

Crie fluxos de trabalho de automação de chamadas no lado do servidor, incluindo sistemas IVR, roteamento de chamadas, gravação e interações com IA.

Instalação

<dependency><groupid>com.azure</groupid><artifactid>azure-communication-callautomation</artifactid><version>1.6.0</version></dependency>

Criação do Cliente

import com.azure.communication.callautomation.CallAutomationClient;
import com.azure.communication.callautomation.CallAutomationClientBuilder;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credencial_específica>
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Ou use uma credencial específica diretamente na produção:
// Consulte https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

// Com DefaultAzureCredential
CallAutomationClient client = new CallAutomationClientBuilder()
    .endpoint("https://<recurso>.communication.azure.com")
    .credential(credential)
    .buildClient();

// Com string de conexão
CallAutomationClient client = new CallAutomationClientBuilder()
    .connectionString("<string-de-conexão>")
    .buildClient();
</string-de-conexão></recurso></credencial_específica>

Conceitos Chave

ClasseFinalidade
`CallAutomationClient`Fazer chamadas, atender/rejeitar chamadas recebidas, redirecionar chamadas
`CallConnection`Ações em chamadas estabelecidas (adicionar participantes, encerrar)
`CallMedia`Operações de mídia (reproduzir áudio, reconhecer DTMF/fala)
`CallRecording`Iniciar/parar/pausar gravação
`CallAutomationEventParser`Analisar eventos de webhook do ACS

Criar Chamada de Saída

import com.azure.communication.callautomation.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import com.azure.communication.common.PhoneNumberIdentifier;

// Chamada para número PSTN
PhoneNumberIdentifier target = new PhoneNumberIdentifier("+14255551234");
PhoneNumberIdentifier caller = new PhoneNumberIdentifier("+14255550100");

CreateCallOptions options = new CreateCallOptions(
    new CommunicationUserIdentifier("<id-do-usuário>"),  // Origem
    List.of(target))                                // Destinos
    .setSourceCallerId(caller)
    .setCallbackUrl("https://seu-app.com/api/callbacks");

CreateCallResult result = client.createCall(options);
String callConnectionId = result.getCallConnectionProperties().getCallConnectionId();
</id-do-usuário>

Atender Chamada Recebida

// Do webhook do Event Grid - Evento IncomingCall
String incomingCallContext = "<contexto-de-chamada-recebida-do-evento>";

AnswerCallOptions options = new AnswerCallOptions(
    incomingCallContext,
    "https://seu-app.com/api/callbacks");

AnswerCallResult result = client.answerCall(options);
CallConnection callConnection = result.getCallConnection();
</contexto-de-chamada-recebida-do-evento>

Reproduzir Áudio (Texto para Fala)

CallConnection callConnection = client.getCallConnection(callConnectionId);
CallMedia callMedia = callConnection.getCallMedia();

// Reproduzir texto para fala
TextSource textSource = new TextSource()
    .setText("Bem-vindo à Contoso. Pressione 1 para vendas, 2 para suporte.")
    .setVoiceName("pt-BR-AntonioNeural");

PlayOptions playOptions = new PlayOptions(
    List.of(textSource),
    List.of(new CommunicationUserIdentifier("<usuario-alvo>")));

callMedia.play(playOptions);

// Reproduzir arquivo de áudio
FileSource fileSource = new FileSource()
    .setUrl("https://storage.blob.core.windows.net/audio/saudacao.wav");

callMedia.play(new PlayOptions(List.of(fileSource), List.of(target)));
</usuario-alvo>

Reconhecer Entrada DTMF

// Reconhecer tons DTMF
DtmfTone stopTones = DtmfTone.POUND;

CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(
    new CommunicationUserIdentifier("<usuario-alvo>"),
    5)  // Máximo de tons a coletar
    .setInterToneTimeout(Duration.ofSeconds(5))
    .setStopTones(List.of(stopTones))
    .setInitialSilenceTimeout(Duration.ofSeconds(15))
    .setPlayPrompt(new TextSource().setText("Digite o número da sua conta seguido de cerquilha."));

callMedia.startRecognizing(recognizeOptions);
</usuario-alvo>

Reconhecer Fala

// Reconhecimento de fala com IA
CallMediaRecognizeSpeechOptions speechOptions = new CallMediaRecognizeSpeechOptions(
    new CommunicationUserIdentifier("<usuario-alvo>"))
    .setEndSilenceTimeout(Duration.ofSeconds(2))
    .setSpeechLanguage("pt-BR")
    .setPlayPrompt(new TextSource().setText("Como posso ajudar você hoje?"));

callMedia.startRecognizing(speechOptions);
</usuario-alvo>

Gravação de Chamada

CallRecording callRecording = client.getCallRecording();

// Iniciar gravação
StartRecordingOptions recordingOptions = new StartRecordingOptions(
    new ServerCallLocator("<id-da-chamada-servidor>"))
    .setRecordingChannel(RecordingChannel.MIXED)
    .setRecordingContent(RecordingContent.AUDIO_VIDEO)
    .setRecordingFormat(RecordingFormat.MP4);

RecordingStateResult recordingResult = callRecording.start(recordingOptions);
String recordingId = recordingResult.getRecordingId();

// Pausar/retomar/parar
callRecording.pause(recordingId);
callRecording.resume(recordingId);
callRecording.stop(recordingId);

// Baixar gravação (após o evento RecordingFileStatusUpdated)
callRecording.downloadTo(recordingUrl, Paths.get("gravacao.mp4"));
</id-da-chamada-servidor>

Adicionar Participante à Chamada

CallConnection callConnection = client.getCallConnection(callConnectionId);

CommunicationUserIdentifier participant = new CommunicationUserIdentifier("<id-do-usuário>");
AddParticipantOptions addOptions = new AddParticipantOptions(participant)
    .setInvitationTimeout(Duration.ofSeconds(30));

AddParticipantResult result = callConnection.addParticipant(addOptions);
</id-do-usuário>

Transferir Chamada

// Transferência cega
PhoneNumberIdentifier transferTarget = new PhoneNumberIdentifier("+14255559999");
TransferCallToParticipantResult result = callConnection.transferCallToParticipant(transferTarget);

Manipular Eventos (Webhook)

import com.azure.communication.callautomation.CallAutomationEventParser;
import com.azure.communication.callautomation.models.events.*;

// No seu endpoint de webhook
public void handleCallback(String requestBody) {
    List<callautomationeventbase> events = CallAutomationEventParser.parseEvents(requestBody);

    for (CallAutomationEventBase event : events) {
        if (event instanceof CallConnected) {
            CallConnected connected = (CallConnected) event;
            System.out.println("Chama conectada: " + connected.getCallConnectionId());
        } else if (event instanceof RecognizeCompleted) {
            RecognizeCompleted recognized = (RecognizeCompleted) event;
            // Manipular resultado do reconhecimento DTMF ou fala
            DtmfResult dtmfResult = (DtmfResult) recognized.getRecognizeResult();
            String tones = dtmfResult.getTones().stream()
                .map(DtmfTone::toString)
                .collect(Collectors.joining());
            System.out.println("DTMF recebido: " + tones);
        } else if (event instanceof PlayCompleted) {
            System.out.println("Reprodução de áudio concluída");
        } else if (event instanceof CallDisconnected) {
            System.out.println("Chama encerrada");
        }
    }
}
</callautomationeventbase>

Desligar Chamada

// Desligar para todos os participantes
callConnection.hangUp(true);

// Desligar apenas este segmento
callConnection.hangUp(false);

Manipulação de Erros

import com.azure.core.exception.HttpResponseException;

try {
    client.answerCall(options);
} catch (HttpResponseException e) {
    if (e.getResponse().getStatusCode() == 404) {
        System.out.println("Chama não encontrada ou já encerrada");
    } else if (e.getResponse().getStatusCode() == 400) {
        System.out.println("Solicitação inválida: " + e.getMessage());
    }
}

Variáveis de Ambiente

AZURE_COMMUNICATION_ENDPOINT=https://<recurso>.communication.azure.com  # Obrigatório para todos os métodos de autenticação
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=...  # Alternativa à autenticação do Entra ID
CALLBACK_BASE_URL=https://seu-app.com/api/callbacks  # Obrigatório para callbacks de webhook
AZURE_TOKEN_CREDENTIALS=prod  # Obrigatório apenas se DefaultAzureCredential for usado na produção
</recurso>

Frases de Gatilho

  • "automação de chamadas Java", "IVR Java", "resposta de voz interativa"
  • "gravação de chamadas Java", "reconhecimento DTMF Java"
  • "texto para fala em chamada", "reconhecimento de fala em chamada"
  • "atender chamada recebida", "transferir chamada Java"
  • "automação de chamadas do Azure Communication Services"
Ver no GitHub
---
name: azure-communication-callautomation-java
description: Build server-side call automation workflows with Azure Communication Services Call Automation Java SDK, including IVR systems, call routing, recording, DTMF recognition, text-to-speech, and AI-powered call flows.
license: MIT
---

# Azure Communication Call Automation (Java)

Build server-side call automation workflows including IVR systems, call routing, recording, and AI-powered interactions.

## Installation

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-callautomation</artifactId>
    <version>1.6.0</version>
</dependency>
```

## Client Creation

```java
import com.azure.communication.callautomation.CallAutomationClient;
import com.azure.communication.callautomation.CallAutomationClientBuilder;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

// With DefaultAzureCredential
CallAutomationClient client = new CallAutomationClientBuilder()
    .endpoint("https://<resource>.communication.azure.com")
    .credential(credential)
    .buildClient();

// With connection string
CallAutomationClient client = new CallAutomationClientBuilder()
    .connectionString("<connection-string>")
    .buildClient();
```

## Key Concepts

| Class | Purpose |
|-------|---------|
| `CallAutomationClient` | Make calls, answer/reject incoming calls, redirect calls |
| `CallConnection` | Actions in established calls (add participants, terminate) |
| `CallMedia` | Media operations (play audio, recognize DTMF/speech) |
| `CallRecording` | Start/stop/pause recording |
| `CallAutomationEventParser` | Parse webhook events from ACS |

## Create Outbound Call

```java
import com.azure.communication.callautomation.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import com.azure.communication.common.PhoneNumberIdentifier;

// Call to PSTN number
PhoneNumberIdentifier target = new PhoneNumberIdentifier("+14255551234");
PhoneNumberIdentifier caller = new PhoneNumberIdentifier("+14255550100");

CreateCallOptions options = new CreateCallOptions(
    new CommunicationUserIdentifier("<user-id>"),  // Source
    List.of(target))                                // Targets
    .setSourceCallerId(caller)
    .setCallbackUrl("https://your-app.com/api/callbacks");

CreateCallResult result = client.createCall(options);
String callConnectionId = result.getCallConnectionProperties().getCallConnectionId();
```

## Answer Incoming Call

```java
// From Event Grid webhook - IncomingCall event
String incomingCallContext = "<incoming-call-context-from-event>";

AnswerCallOptions options = new AnswerCallOptions(
    incomingCallContext,
    "https://your-app.com/api/callbacks");

AnswerCallResult result = client.answerCall(options);
CallConnection callConnection = result.getCallConnection();
```

## Play Audio (Text-to-Speech)

```java
CallConnection callConnection = client.getCallConnection(callConnectionId);
CallMedia callMedia = callConnection.getCallMedia();

// Play text-to-speech
TextSource textSource = new TextSource()
    .setText("Welcome to Contoso. Press 1 for sales, 2 for support.")
    .setVoiceName("en-US-JennyNeural");

PlayOptions playOptions = new PlayOptions(
    List.of(textSource),
    List.of(new CommunicationUserIdentifier("<target-user>")));

callMedia.play(playOptions);

// Play audio file
FileSource fileSource = new FileSource()
    .setUrl("https://storage.blob.core.windows.net/audio/greeting.wav");

callMedia.play(new PlayOptions(List.of(fileSource), List.of(target)));
```

## Recognize DTMF Input

```java
// Recognize DTMF tones
DtmfTone stopTones = DtmfTone.POUND;

CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(
    new CommunicationUserIdentifier("<target-user>"),
    5)  // Max tones to collect
    .setInterToneTimeout(Duration.ofSeconds(5))
    .setStopTones(List.of(stopTones))
    .setInitialSilenceTimeout(Duration.ofSeconds(15))
    .setPlayPrompt(new TextSource().setText("Enter your account number followed by pound."));

callMedia.startRecognizing(recognizeOptions);
```

## Recognize Speech

```java
// Speech recognition with AI
CallMediaRecognizeSpeechOptions speechOptions = new CallMediaRecognizeSpeechOptions(
    new CommunicationUserIdentifier("<target-user>"))
    .setEndSilenceTimeout(Duration.ofSeconds(2))
    .setSpeechLanguage("en-US")
    .setPlayPrompt(new TextSource().setText("How can I help you today?"));

callMedia.startRecognizing(speechOptions);
```

## Call Recording

```java
CallRecording callRecording = client.getCallRecording();

// Start recording
StartRecordingOptions recordingOptions = new StartRecordingOptions(
    new ServerCallLocator("<server-call-id>"))
    .setRecordingChannel(RecordingChannel.MIXED)
    .setRecordingContent(RecordingContent.AUDIO_VIDEO)
    .setRecordingFormat(RecordingFormat.MP4);

RecordingStateResult recordingResult = callRecording.start(recordingOptions);
String recordingId = recordingResult.getRecordingId();

// Pause/resume/stop
callRecording.pause(recordingId);
callRecording.resume(recordingId);
callRecording.stop(recordingId);

// Download recording (after RecordingFileStatusUpdated event)
callRecording.downloadTo(recordingUrl, Paths.get("recording.mp4"));
```

## Add Participant to Call

```java
CallConnection callConnection = client.getCallConnection(callConnectionId);

CommunicationUserIdentifier participant = new CommunicationUserIdentifier("<user-id>");
AddParticipantOptions addOptions = new AddParticipantOptions(participant)
    .setInvitationTimeout(Duration.ofSeconds(30));

AddParticipantResult result = callConnection.addParticipant(addOptions);
```

## Transfer Call

```java
// Blind transfer
PhoneNumberIdentifier transferTarget = new PhoneNumberIdentifier("+14255559999");
TransferCallToParticipantResult result = callConnection.transferCallToParticipant(transferTarget);
```

## Handle Events (Webhook)

```java
import com.azure.communication.callautomation.CallAutomationEventParser;
import com.azure.communication.callautomation.models.events.*;

// In your webhook endpoint
public void handleCallback(String requestBody) {
    List<CallAutomationEventBase> events = CallAutomationEventParser.parseEvents(requestBody);
    
    for (CallAutomationEventBase event : events) {
        if (event instanceof CallConnected) {
            CallConnected connected = (CallConnected) event;
            System.out.println("Call connected: " + connected.getCallConnectionId());
        } else if (event instanceof RecognizeCompleted) {
            RecognizeCompleted recognized = (RecognizeCompleted) event;
            // Handle DTMF or speech recognition result
            DtmfResult dtmfResult = (DtmfResult) recognized.getRecognizeResult();
            String tones = dtmfResult.getTones().stream()
                .map(DtmfTone::toString)
                .collect(Collectors.joining());
            System.out.println("DTMF received: " + tones);
        } else if (event instanceof PlayCompleted) {
            System.out.println("Audio playback completed");
        } else if (event instanceof CallDisconnected) {
            System.out.println("Call ended");
        }
    }
}
```

## Hang Up Call

```java
// Hang up for all participants
callConnection.hangUp(true);

// Hang up only this leg
callConnection.hangUp(false);
```

## Error Handling

```java
import com.azure.core.exception.HttpResponseException;

try {
    client.answerCall(options);
} catch (HttpResponseException e) {
    if (e.getResponse().getStatusCode() == 404) {
        System.out.println("Call not found or already ended");
    } else if (e.getResponse().getStatusCode() == 400) {
        System.out.println("Invalid request: " + e.getMessage());
    }
}
```

## Environment Variables

```bash
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com  # Required for all auth methods
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=...  # Alternative to Entra ID auth
CALLBACK_BASE_URL=https://your-app.com/api/callbacks  # Required for webhook callbacks
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production
```

## Trigger Phrases

- "call automation Java", "IVR Java", "interactive voice response"
- "call recording Java", "DTMF recognition Java"
- "text to speech call", "speech recognition call"
- "answer incoming call", "transfer call Java"
- "Azure Communication Services call automation"

Todos os arquivos

0 arquivos

Instalar azure-communication-callautomation-java

Baixe e extraia os arquivos de habilidade para o diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-communication-callautomation-java # Copy SKILL.md to your .claude/skills/ directory

Copiar Copiar
Configuração rápida: Copie a pasta de habilidades para .claude/skills/ O Claude detectará e usará automaticamente a habilidade
Repositório microsoft/skills

Habilidades relacionadas

brightdata-cli
Tempo atualizado 29 de Junho de 2026
humanize
Tempo atualizado 7 de Julho de 2026
agentwallet
Tempo atualizado 7 de Julho de 2026
korean-stock-search
Tempo atualizado 8 de Julho de 2026
OR