Automatisation d'appels Azure Communication (Java)
Créez des flux de travail d'automatisation d'appels côté serveur, notamment des systèmes IVR, l'acheminement d'appels, l'enregistrement et les interactions alimentées par l'IA.
Installation
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-callautomation</artifactId>
<version>1.6.0</version>
</dependency>
Création du client
import com.azure.communication.callautomation.CallAutomationClient;
import com.azure.communication.callautomation.CallAutomationClientBuilder;
import com.azure.identity.DefaultAzureCredentialBuilder;
// Avec DefaultAzureCredential
CallAutomationClient client = new CallAutomationClientBuilder()
.endpoint("https://<resource>.communication.azure.com")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
// Avec chaîne de connexion
CallAutomationClient client = new CallAutomationClientBuilder()
.connectionString("<connection-string>")
.buildClient();
Concepts clés
| Classe | Objectif |
|---|---|
CallAutomationClient |
Passer des appels, répondre/rejeter les appels entrants, rediriger les appels |
CallConnection |
Actions dans les appels établis (ajouter des participants, terminer) |
CallMedia |
Opérations multimédias (lire l'audio, reconnaître DTMF/parole) |
CallRecording |
Démarrer/arrêter/suspendre l'enregistrement |
CallAutomationEventParser |
Analyser les événements webhook d'ACS |
Créer un appel sortant
import com.azure.communication.callautomation.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import com.azure.communication.common.PhoneNumberIdentifier;
// Appel vers un numéro PSTN
PhoneNumberIdentifier target = new PhoneNumberIdentifier("+14255551234");
PhoneNumberIdentifier caller = new PhoneNumberIdentifier("+14255550100");
CreateCallOptions options = new CreateCallOptions(
new CommunicationUserIdentifier("<user-id>"), // Source
List.of(target)) // Cibles
.setSourceCallerId(caller)
.setCallbackUrl("https://your-app.com/api/callbacks");
CreateCallResult result = client.createCall(options);
String callConnectionId = result.getCallConnectionProperties().getCallConnectionId();
Répondre à un appel entrant
// À partir du webhook Event Grid - événement 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();
Lire l'audio (synthèse vocale)
CallConnection callConnection = client.getCallConnection(callConnectionId);
CallMedia callMedia = callConnection.getCallMedia();
// Lire la synthèse vocale
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);
// Lire un fichier audio
FileSource fileSource = new FileSource()
.setUrl("https://storage.blob.core.windows.net/audio/greeting.wav");
callMedia.play(new PlayOptions(List.of(fileSource), List.of(target)));
Reconnaître l'entrée DTMF
// Reconnaître les tonalités DTMF
DtmfTone stopTones = DtmfTone.POUND;
CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(
new CommunicationUserIdentifier("<target-user>"),
5) // Tonalités max à collecter
.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);
Reconnaître la parole
// Reconnaissance vocale avec IA
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);
Enregistrement d'appel
CallRecording callRecording = client.getCallRecording();
// Démarrer l'enregistrement
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();
// Suspendre/reprendre/arrêter
callRecording.pause(recordingId);
callRecording.resume(recordingId);
callRecording.stop(recordingId);
// Télécharger l'enregistrement (après l'événement RecordingFileStatusUpdated)
callRecording.downloadTo(recordingUrl, Paths.get("recording.mp4"));
Ajouter un participant à l'appel
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);
Transférer l'appel
// Transfert sans consultation
PhoneNumberIdentifier transferTarget = new PhoneNumberIdentifier("+14255559999");
TransferCallToParticipantResult result = callConnection.transferCallToParticipant(transferTarget);
Gérer les événements (Webhook)
import com.azure.communication.callautomation.CallAutomationEventParser;
import com.azure.communication.callautomation.models.events.*;
// Dans votre point de terminaison 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("Call connected: " + connected.getCallConnectionId());
} else if (event instanceof RecognizeCompleted) {
RecognizeCompleted recognized = (RecognizeCompleted) event;
// Gérer le résultat de la reconnaissance DTMF ou vocale
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");
}
}
}
Raccrocher
// Raccrocher pour tous les participants
callConnection.hangUp(true);
// Raccrocher uniquement cette liaison
callConnection.hangUp(false);
Gestion des erreurs
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());
}
}
Variables d'environnement
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=...
CALLBACK_BASE_URL=https://your-app.com/api/callbacks
Expressions déclencheurs
- "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"