azure-communication-callautomation-java
microsoft/skills
Создавайте автоматизированные рабочие процессы серверных вызовов с помощью Azure Communication Services Call Automation Java SDK, включая системы IVR, маршрутизацию вызовов, запись, распознавание DTMF, преобразование текста в речь и управляемые ИИ потоки вызовов.
...Расширить всеAzure Communication Call Automation (Java)
Создавайте серверные рабочие процессы автоматизации звонков, включая системы IVR, маршрутизацию звонков, запись и взаимодействия на основе искусственного интеллекта.
Установка
<dependency><groupid>com.azure</groupid><artifactid>azure-communication-callautomation</artifactid><version>1.6.0</version></dependency>Создание клиента
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;
// Локальная разработка: DefaultAzureCredential. Продукция: установите AZURE_TOKEN_CREDENTIALS=prod или AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// Или используйте конкретные учетные данные напрямую в продуктиве:
// См. https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
// С DefaultAzureCredential
CallAutomationClient client = new CallAutomationClientBuilder()
.endpoint("https://<resource>.communication.azure.com")
.credential(credential)
.buildClient();
// С строкой подключения
CallAutomationClient client = new CallAutomationClientBuilder()
.connectionString("<connection-string>")
.buildClient();
</connection-string></resource></specific_credential>Ключевые концепции
| Класс | Назначение |
|---|---|
| `CallAutomationClient` | Совершение вызовов, ответ/отклонение входящих вызовов, перенаправление вызовов |
| `CallConnection` | Действия в установленных вызовах (добавление участников, завершение) |
| `CallMedia` | Медиаоперации (воспроизведение аудио, распознавание DTMF/речи) |
| `CallRecording` | Запуск/остановка/пауза записи |
| `CallAutomationEventParser` | Разбор событий веб-перехватчика от ACS |
Создание исходящего вызова
import com.azure.communication.callautomation.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import com.azure.communication.common.PhoneNumberIdentifier;
// Вызов на номер PSTN
PhoneNumberIdentifier target = new PhoneNumberIdentifier("+14255551234");
PhoneNumberIdentifier caller = new PhoneNumberIdentifier("+14255550100");
CreateCallOptions options = new CreateCallOptions(
new CommunicationUserIdentifier("<user-id>"), // Источник
List.of(target)) // Цели
.setSourceCallerId(caller)
.setCallbackUrl("https://your-app.com/api/callbacks");
CreateCallResult result = client.createCall(options);
String callConnectionId = result.getCallConnectionProperties().getCallConnectionId();
</user-id>Ответ на входящий вызов
// Из веб-перехватчика Event Grid - событие IncomingCall
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();
</incoming-call-context-from-event>Воспроизведение аудио (синтез речи)
CallConnection callConnection = client.getCallConnection(callConnectionId);
CallMedia callMedia = callConnection.getCallMedia();
// Воспроизведение текста в речь
TextSource textSource = new TextSource()
.setText("Добро пожаловать в Contoso. Нажмите 1 для отдела продаж, 2 для поддержки.")
.setVoiceName("en-US-JennyNeural");
PlayOptions playOptions = new PlayOptions(
List.of(textSource),
List.of(new CommunicationUserIdentifier("<target-user>")));
callMedia.play(playOptions);
// Воспроизведение аудиофайла
FileSource fileSource = new FileSource()
.setUrl("https://storage.blob.core.windows.net/audio/greeting.wav");
callMedia.play(new PlayOptions(List.of(fileSource), List.of(target)));
</target-user>Распознавание ввода DTMF
// Распознавание тонов DTMF
DtmfTone stopTones = DtmfTone.POUND;
CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(
new CommunicationUserIdentifier("<target-user>"),
5) // Максимальное количество собираемых тонов
.setInterToneTimeout(Duration.ofSeconds(5))
.setStopTones(List.of(stopTones))
.setInitialSilenceTimeout(Duration.ofSeconds(15))
.setPlayPrompt(new TextSource().setText("Введите номер вашей учетной записи, затем рештку."));
callMedia.startRecognizing(recognizeOptions);
</target-user>Распознавание речи
// Распознавание речи с использованием ИИ
CallMediaRecognizeSpeechOptions speechOptions = new CallMediaRecognizeSpeechOptions(
new CommunicationUserIdentifier("<target-user>"))
.setEndSilenceTimeout(Duration.ofSeconds(2))
.setSpeechLanguage("en-US")
.setPlayPrompt(new TextSource().setText("Чем я могу вам помочь сегодня?"));
callMedia.startRecognizing(speechOptions);
</target-user>Запись звонка
CallRecording callRecording = client.getCallRecording();
// Запуск записи
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();
// Пауза/возобновление/остановка
callRecording.pause(recordingId);
callRecording.resume(recordingId);
callRecording.stop(recordingId);
// Скачивание записи (после события RecordingFileStatusUpdated)
callRecording.downloadTo(recordingUrl, Paths.get("recording.mp4"));
</server-call-id>Добавление участника в вызов
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);
</user-id>Перенаправление вызова
// Слепое перенаправление
PhoneNumberIdentifier transferTarget = new PhoneNumberIdentifier("+14255559999");
TransferCallToParticipantResult result = callConnection.transferCallToParticipant(transferTarget);
Обработка событий (веб-перехватчик)
import com.azure.communication.callautomation.CallAutomationEventParser;
import com.azure.communication.callautomation.models.events.*;
// В вашей конечной точке веб-перехватчика
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("Вызов установлен: " + connected.getCallConnectionId());
} else if (event instanceof RecognizeCompleted) {
RecognizeCompleted recognized = (RecognizeCompleted) event;
// Обработка результата распознавания DTMF или речи
DtmfResult dtmfResult = (DtmfResult) recognized.getRecognizeResult();
String tones = dtmfResult.getTones().stream()
.map(DtmfTone::toString)
.collect(Collectors.joining());
System.out.println("Получен DTMF: " + tones);
} else if (event instanceof PlayCompleted) {
System.out.println("Воспроизведение аудио завершено");
} else if (event instanceof CallDisconnected) {
System.out.println("Вызов завершен");
}
}
}
</callautomationeventbase>Завершение вызова
// Завершить для всех участников
callConnection.hangUp(true);
// Завершить только этот канал
callConnection.hangUp(false);
Обработка ошибок
import com.azure.core.exception.HttpResponseException;
try {
client.answerCall(options);
} catch (HttpResponseException e) {
if (e.getResponse().getStatusCode() == 404) {
System.out.println("Вызов не найден или уже завершен");
} else if (e.getResponse().getStatusCode() == 400) {
System.out.println("Неверный запрос: " + e.getMessage());
}
}
Переменные среды
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com # Требуется для всех методов аутентификации
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=... # Альтернатива аутентификации Entra ID
CALLBACK_BASE_URL=https://your-app.com/api/callbacks # Требуется для обратных вызовов веб-перехватчика
AZURE_TOKEN_CREDENTIALS=prod # Требуется только если DefaultAzureCredential используется в продуктиве
</resource>Триггерные фразы
- "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"
---
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"
Все файлы
0 файловУстановить azure-communication-callautomation-java
Скачайте и извлеките файлы навыков в директорию .claude/skills/.
Скачать ZIPКлонируйте репозиторий и скопируйте файлы навыка в свой проект.
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
Копировать





Дом
