关于 azure-communication-callautomation-java
面向 Java 开发者的 Azure Communication Services 呼叫自动化技能,涵盖服务端 IVR 与通话工作流。内容包括通话控制、媒体识别、录音和 Webhook 事件处理。
主要功能
- 01创建、接听、拒绝和重定向通话
- 02播放文本转语音音频
- 03识别 DTMF 和语音
- 04开始、暂停和停止录音
- 05处理通话 Webhook 事件
适用场景
- 01构建带菜单提示的 IVR
- 02路由或转接来电
- 03收集按键或语音响应
- 04在取得适当同意后录音
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-communication-callautomation-java安装后在 Claude Code 中输入/azure-communication-callautomation-java确认已加载。
详细介绍
Azure Communication 呼叫自动化(Java)
构建服务端呼叫自动化工作流,包括 IVR 系统、呼叫路由、录音和 AI 驱动的交互。
集成边界
示例是针对指定 SDK 版本的代码片段,并非完整的 IVR。编译前,请核对该版本中的构造函数和类型。外呼和呼叫转接会产生费用,且需要使用获批的接收方;录音需要适当告知并征得同意,同时妥善保护录音数据。对 Webhook 投递进行身份验证,验证事件架构,去重事件 ID 和操作 ID,并避免记录 DTMF 或账户数据。异步请求已受理,并不表示播放或识别已成功:请处理失败和断开连接事件。
安装
<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.identity.DefaultAzureCredentialBuilder;
// With DefaultAzureCredential
CallAutomationClient client = new CallAutomationClientBuilder()
.endpoint("https://<resource>.communication.azure.com")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
// With connection string
CallAutomationClient client = new CallAutomationClientBuilder()
.connectionString("<connection-string>")
.buildClient();
核心概念
| 类 | 用途 |
|---|---|
CallAutomationClient | 发起呼叫、接听或拒绝来电、重定向呼叫 |
CallConnection | 已建立呼叫中的操作(添加参与者、终止呼叫) |
CallMedia | 媒体操作(播放音频、识别 DTMF/语音) |
CallRecording | 开始、停止或暂停录音 |
CallAutomationEventParser | 解析来自 ACS 的 Webhook 事件 |
创建外呼
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();
接听来电
// 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();
播放音频(文本转语音)
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)));
识别 DTMF 输入
// 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);
识别语音
// 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);
呼叫录音
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"));
向呼叫中添加参与者
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);
转接呼叫
// Blind transfer
PhoneNumberIdentifier transferTarget = new PhoneNumberIdentifier("+14255559999");
TransferCallToParticipantResult result = callConnection.transferCallToParticipant(transferTarget);
处理事件(Webhook)
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
if (!(recognized.getRecognizeResult() instanceof DtmfResult)) {
// Handle speech results in a separate branch.
continue;
}
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 for all participants
callConnection.hangUp(true);
// Hang up only this leg
callConnection.hangUp(false);
错误处理
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());
}
}
环境变量
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com
AZURE_COMMUNICATION_CONNECTION_STRING=endpoint=https://...;accesskey=...
CALLBACK_BASE_URL=https://your-app.com/api/callbacks
触发短语
- “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”
适用场景
此技能适用于执行概述中所述的工作流或操作。
限制
- 仅当任务明确符合上述范围时,才使用此技能。
- 不要将输出视为环境特定验证、测试或专家审查的替代品。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。
评论
支持 Markdown