你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:使用通话自动化进行出站呼叫

Azure 通信服务通话自动化 API 是创建交互式通话体验的有效方法。 本快速入门将介绍一种进行出站呼叫并识别通话中各种事件的方法。

先决条件

代码示例

GitHub 下载或克隆快速入门示例代码。

导航到 CallAutomation_OutboundCalling 文件夹并在代码编辑器中打开解决方案。

设置并托管 Azure DevTunnel

Azure DevTunnels 是一项 Azure 服务,可用于共享 Internet 上托管的本地 Web 服务。 运行以下命令,将本地开发环境连接到公共 Internet。 DevTunnels 会创建一个永久性终结点 URL,可用于匿名访问。 我们使用此终结点通知你的应用程序来自 Azure 通信服务通话自动化服务的通话事件。

devtunnel create --allow-anonymous
devtunnel port create -p 8080
devtunnel host

更新应用程序配置

接下来使用以下值更新 Program.cs 文件:

  • acsConnectionString:Azure 通信服务资源的连接字符串。 可以按照此处的说明查找 Azure 通信服务连接字符串。
  • callbackUriHost:初始化 DevTunnel 主机后,使用 URI 更新此字段。
  • acsPhonenumber:使用获取的 Azure 通信服务电话号码更新此字段。 此电话号码应使用 E164 电话号码格式(例如 +18881234567)
  • targetPhonenumber:使用你希望应用程序呼叫的电话号码更新此字段。 此电话号码应使用 E164 电话号码格式(例如 +18881234567)
  • cognitiveServiceEndpoint:使用 Azure AI 服务终结点更新字段。
  • targetTeamsUserId:(可选)使用要添加到呼叫的 Microsoft Teams 用户 ID 来更新字段。 请参阅使用图形 API 获取 Teams 用户 ID
// Your ACS resource connection string 
var acsConnectionString = "<ACS_CONNECTION_STRING>"; 

// Your ACS resource phone number will act as source number to start outbound call 
var acsPhonenumber = "<ACS_PHONE_NUMBER>"; 
 
// Target phone number you want to receive the call. 
var targetPhonenumber = "<TARGET_PHONE_NUMBER>";

// Base url of the app 
var callbackUriHost = "<CALLBACK_URI_HOST_WITH_PROTOCOL>"; 

// Your cognitive service endpoint 
var cognitiveServiceEndpoint = "<COGNITIVE_SERVICE_ENDPOINT>";

// (Optional) User Id of the target teams user you want to receive the call.
var targetTeamsUserId = "<TARGET_TEAMS_USER_ID>";

发起传出通话

若要从 Azure 通信服务进行出站呼叫,此示例使用之前在应用程序中定义的 targetPhonenumber 来通过 CreateCallAsync API 创建呼叫。 此代码将使用目标电话号码进行出站呼叫。

PhoneNumberIdentifier target = new PhoneNumberIdentifier(targetPhonenumber);
PhoneNumberIdentifier caller = new PhoneNumberIdentifier(acsPhonenumber);
var callbackUri = new Uri(callbackUriHost + "/api/callbacks");
CallInvite callInvite = new CallInvite(target, caller);
var createCallOptions = new CreateCallOptions(callInvite, callbackUri) {
  CallIntelligenceOptions = new CallIntelligenceOptions() {
    CognitiveServicesEndpoint = new Uri(cognitiveServiceEndpoint)
  }
};
CreateCallResult createCallResult = await callAutomationClient.CreateCallAsync(createCallOptions);

处理通话自动化事件

在之前的应用程序中,我们已将 callbackUriHost 注册到通话自动化服务。 主机指示服务所需的终结点,以便通知我们发生的通话事件。 然后,我们可以循环访问事件并检测应用程序需要了解的特定事件。 下面的代码响应 CallConnected 事件。

app.MapPost("/api/callbacks", async (CloudEvent[] cloudEvents, ILogger < Program > logger) => {
  foreach(var cloudEvent in cloudEvents) {
    logger.LogInformation($"Event received: {JsonConvert.SerializeObject(cloudEvent)}");
    CallAutomationEventBase parsedEvent = CallAutomationEventParser.Parse(cloudEvent);
    logger.LogInformation($"{parsedEvent?.GetType().Name} parsedEvent received for call connection id: {parsedEvent?.CallConnectionId}");
    var callConnection = callAutomationClient.GetCallConnection(parsedEvent.CallConnectionId);
    var callMedia = callConnection.GetCallMedia();
    if (parsedEvent is CallConnected) {
      //Handle Call Connected Event
    }
  }
});

(可选)将 Microsoft Teams 用户添加到呼叫

可以使用 AddParticipantAsync 方法通过 MicrosoftTeamsUserIdentifier 和 Teams 用户 ID 将 Microsoft Teams 用户添加到呼叫。首先需要完成先决条件步骤“向 Azure 通信服务资源授权以允许呼叫 Microsoft Teams 用户”。 (可选)还可以传入 SourceDisplayName 来控制 Teams 用户的 Toast 通知中显示的文本。

await callConnection.AddParticipantAsync(
    new CallInvite(new MicrosoftTeamsUserIdentifier(targetTeamsUserId))
    {
        SourceDisplayName = "Jack (Contoso Tech Support)"
    });

开始录制通话

通话自动化服务还支持开始录制和存储语音和视频通话的录制内容。 有关通话记录 API 的各种功能的详细信息,请参阅此处

CallLocator callLocator = new ServerCallLocator(parsedEvent.ServerCallId);
var recordingResult = await callAutomationClient.GetCallRecording().StartAsync(new StartRecordingOptions(callLocator));
recordingId = recordingResult.Value.RecordingId;

播放欢迎消息并识别身份

使用 TextSource,可以向服务提供想要合成并用于欢迎信息的文本。 Azure 通信服务通话自动化服务在发生 CallConnected 事件时播放此消息。

接下来,将该文本传递到 CallMediaRecognizeChoiceOptions,然后呼叫 StartRecognizingAsync。 这样应用程序就可以识别呼叫者选择的选项。

if (parsedEvent is CallConnected callConnected) {
  logger.LogInformation($"Start Recording...");
  CallLocator callLocator = new ServerCallLocator(parsedEvent.ServerCallId);
  var recordingResult = await callAutomationClient.GetCallRecording().StartAsync(new StartRecordingOptions(callLocator));
  recordingId = recordingResult.Value.RecordingId;

  var choices = GetChoices();

  // prepare recognize tones 
  var recognizeOptions = GetMediaRecognizeChoiceOptions(mainMenu, targetPhonenumber, choices);

  // Send request to recognize tones 
  await callMedia.StartRecognizingAsync(recognizeOptions);
}

CallMediaRecognizeChoiceOptions GetMediaRecognizeChoiceOptions(string content, string targetParticipant, List < RecognitionChoice > choices, string context = "") {
  var playSource = new TextSource(content) {
    VoiceName = SpeechToTextVoice
  };

  var recognizeOptions = new CallMediaRecognizeChoiceOptions(targetParticipant: new PhoneNumberIdentifier(targetParticipant), choices) {
    InterruptCallMediaOperation = false,
      InterruptPrompt = false,
      InitialSilenceTimeout = TimeSpan.FromSeconds(10),
      Prompt = playSource,
      OperationContext = context
  };
  return recognizeOptions;
}

List < RecognitionChoice > GetChoices() {
  return new List < RecognitionChoice > {
    new RecognitionChoice("Confirm", new List < string > {
      "Confirm",
      "First",
      "One"
    }) {
      Tone = DtmfTone.One
    },
    new RecognitionChoice("Cancel", new List < string > {
      "Cancel",
      "Second",
      "Two"
    }) {
      Tone = DtmfTone.Two
    }
  };
}

处理选择事件

Azure 通信服务通话自动化会对已设置的 Webhook 触发 api/callbacks,并通知我们发生了 RecognizeCompleted 事件。 此事件使我们能够响应接收到的输入并触发操作。 然后,应用程序根据接收到的特定输入向呼叫者播放消息。

if (parsedEvent is RecognizeCompleted recognizeCompleted) {
  var choiceResult = recognizeCompleted.RecognizeResult as ChoiceResult;
  var labelDetected = choiceResult?.Label;
  var phraseDetected = choiceResult?.RecognizedPhrase;

  // If choice is detected by phrase, choiceResult.RecognizedPhrase will have the phrase detected,  
  // If choice is detected using dtmf tone, phrase will be null  
  logger.LogInformation("Recognize completed succesfully, labelDetected={labelDetected}, phraseDetected={phraseDetected}", labelDetected, phraseDetected);

  var textToPlay = labelDetected.Equals(ConfirmChoiceLabel, StringComparison.OrdinalIgnoreCase) ? ConfirmedText : CancelText;

  await HandlePlayAsync(callMedia, textToPlay);
}

async Task HandlePlayAsync(CallMedia callConnectionMedia, string text) {
  // Play goodbye message 
  var GoodbyePlaySource = new TextSource(text) {
    VoiceName = "en-US-NancyNeural"
  };
  await callConnectionMedia.PlayToAllAsync(GoodbyePlaySource);
}

挂断并停止录制

最后,当检测到需要终止通话的情况时,可以使用 HangUpAsync 方法挂断通话。

if ((parsedEvent is PlayCompleted) || (parsedEvent is PlayFailed))
{
    logger.LogInformation($"Stop recording and terminating call.");
    callAutomationClient.GetCallRecording().Stop(recordingId);
    await callConnection.HangUpAsync(true);
}

运行代码

若要使用 VS Code 运行应用程序,请打开终端窗口并运行以下命令

dotnet run

先决条件

代码示例

GitHub 下载或克隆快速入门示例代码。

导航到 CallAutomation_OutboundCalling 文件夹并在代码编辑器中打开解决方案。

设置并托管 Azure DevTunnel

Azure DevTunnels 是一项 Azure 服务,可用于共享 Internet 上托管的本地 Web 服务。 运行 DevTunnel 命令,将本地开发环境连接到公共 Internet。 然后,DevTunnel 会创建一个具有永久性终结点 URL 的隧道,可用于匿名访问。 Azure 通信服务使用此终结点通知你的应用程序来自 Azure 通信服务通话自动化服务的通话事件。

devtunnel create --allow-anonymous
devtunnel port create -p MY_SPRINGAPP_PORT
devtunnel host

更新应用程序配置

然后打开 /resources 文件夹中的 application.yml 文件以配置以下值:

  • connectionstring:Azure 通信服务资源的连接字符串。 可以按照此处的说明查找 Azure 通信服务连接字符串。
  • basecallbackuri:初始化 DevTunnel 主机后,使用 URI 更新此字段。
  • callerphonenumber:使用获取的 Azure 通信服务电话号码更新此字段。 此电话号码应使用 E164 电话号码格式(例如 +18881234567)
  • targetphonenumber:使用你希望应用程序呼叫的电话号码更新此字段。 此电话号码应使用 E164 电话号码格式(例如 +18881234567)
  • cognitiveServiceEndpoint:使用 Azure AI 服务终结点更新字段。
  • targetTeamsUserId:(可选)使用要添加到呼叫的 Microsoft Teams 用户 ID 来更新字段。 请参阅使用图形 API 获取 Teams 用户 ID
acs:
  connectionstring: <YOUR ACS CONNECTION STRING> 
  basecallbackuri: <YOUR DEV TUNNEL ENDPOINT> 
  callerphonenumber: <YOUR ACS PHONE NUMBER ex. "+1425XXXAAAA"> 
  targetphonenumber: <YOUR TARGET PHONE NUMBER ex. "+1425XXXAAAA"> 
  cognitiveServiceEndpoint: <YOUR COGNITIVE SERVICE ENDPOINT>
  targetTeamsUserId: <(OPTIONAL) YOUR TARGET TEAMS USER ID ex. "ab01bc12-d457-4995-a27b-c405ecfe4870">

进行出站呼叫并播放媒体

若要从 Azure 通信服务进行出站呼叫,此示例使用在 application.yml 文件中定义的 targetphonenumber 来通过 createCallWithResponse API 创建呼叫。

PhoneNumberIdentifier caller = new PhoneNumberIdentifier(appConfig.getCallerphonenumber());
PhoneNumberIdentifier target = new PhoneNumberIdentifier(appConfig.getTargetphonenumber());
CallInvite callInvite = new CallInvite(target, caller);
CreateCallOptions createCallOptions = new CreateCallOptions(callInvite, appConfig.getCallBackUri());
CallIntelligenceOptions callIntelligenceOptions = new CallIntelligenceOptions().setCognitiveServicesEndpoint(appConfig.getCognitiveServiceEndpoint());
createCallOptions = createCallOptions.setCallIntelligenceOptions(callIntelligenceOptions);
Response<CreateCallResult> result = client.createCallWithResponse(createCallOptions, Context.NONE);

(可选)将 Microsoft Teams 用户添加到呼叫

可以使用 addParticipant 方法通过 MicrosoftTeamsUserIdentifier 和 Teams 用户 ID 将 Microsoft Teams 用户添加到呼叫。首先需要完成先决条件步骤“向 Azure 通信服务资源授权以允许呼叫 Microsoft Teams 用户”。 (可选)还可以传入 SourceDisplayName 来控制 Teams 用户的 Toast 通知中显示的文本。

client.getCallConnection(callConnectionId).addParticipant(
    new CallInvite(new MicrosoftTeamsUserIdentifier(targetTeamsUserId))
        .setSourceDisplayName("Jack (Contoso Tech Support)"));

开始录制通话

通话自动化服务还支持开始录制和存储语音和视频通话的录制内容。 有关通话记录 API 的各种功能的详细信息,请参阅此处

ServerCallLocator serverCallLocator = new ServerCallLocator(
    client.getCallConnection(callConnectionId)
        .getCallProperties()
        .getServerCallId());
        
StartRecordingOptions startRecordingOptions = new StartRecordingOptions(serverCallLocator);

Response<RecordingStateResult> response = client.getCallRecording()
    .startWithResponse(startRecordingOptions, Context.NONE);

recordingId = response.getValue().getRecordingId();

响应通话事件

在之前的应用程序中,我们已将 basecallbackuri 注册到通话自动化服务。 URI 指示服务要使用的终结点,以便通知我们发生的通话事件。 然后,我们可以循环访问事件并检测应用程序需要了解的特定事件。 下面的代码响应 CallConnected 事件。

List<CallAutomationEventBase> events = CallAutomationEventParser.parseEvents(reqBody);
for (CallAutomationEventBase event : events) {
    String callConnectionId = event.getCallConnectionId();
    if (event instanceof CallConnected) {
        log.info("CallConnected event received");
    }
    else if (event instanceof RecognizeCompleted) {
        log.info("Recognize Completed event received");
    }
}

播放欢迎消息并识别身份

使用 TextSource,可以向服务提供想要合成并用于欢迎信息的文本。 Azure 通信服务通话自动化服务在发生 CallConnected 事件时播放此消息。

接下来,将该文本传递到 CallMediaRecognizeChoiceOptions,然后呼叫 StartRecognizingAsync。 这样应用程序就可以识别呼叫者选择的选项。

var playSource = new TextSource().setText(content).setVoiceName("en-US-NancyNeural");

var recognizeOptions = new CallMediaRecognizeChoiceOptions(new PhoneNumberIdentifier(targetParticipant), getChoices())
  .setInterruptCallMediaOperation(false)
  .setInterruptPrompt(false)
  .setInitialSilenceTimeout(Duration.ofSeconds(10))
  .setPlayPrompt(playSource)
  .setOperationContext(context);

client.getCallConnection(callConnectionId)
  .getCallMedia()
  .startRecognizing(recognizeOptions);

private List < RecognitionChoice > getChoices() {
  var choices = Arrays.asList(
    new RecognitionChoice().setLabel(confirmLabel).setPhrases(Arrays.asList("Confirm", "First", "One")).setTone(DtmfTone.ONE),
    new RecognitionChoice().setLabel(cancelLabel).setPhrases(Arrays.asList("Cancel", "Second", "Two")).setTone(DtmfTone.TWO)
  );

  return choices;
}

处理选择事件

Azure 通信服务通话自动化会对已设置的 Webhook 触发 api/callbacks,并通知我们发生了 RecognizeCompleted 事件。 此事件使我们能够响应接收到的输入并触发操作。 然后,应用程序根据接收到的特定输入向呼叫者播放消息。

else if (event instanceof RecognizeCompleted) {
  log.info("Recognize Completed event received");

  RecognizeCompleted acsEvent = (RecognizeCompleted) event;

  var choiceResult = (ChoiceResult) acsEvent.getRecognizeResult().get();

  String labelDetected = choiceResult.getLabel();

  String phraseDetected = choiceResult.getRecognizedPhrase();

  log.info("Recognition completed, labelDetected=" + labelDetected + ", phraseDetected=" + phraseDetected + ", context=" + event.getOperationContext());

  String textToPlay = labelDetected.equals(confirmLabel) ? confirmedText : cancelText;

  handlePlay(callConnectionId, textToPlay);
}

private void handlePlay(final String callConnectionId, String textToPlay) {
  var textPlay = new TextSource()
    .setText(textToPlay)
    .setVoiceName("en-US-NancyNeural");

  client.getCallConnection(callConnectionId)
    .getCallMedia()
    .playToAll(textPlay);
}

挂断呼叫

最后,当检测到需要终止通话的情况时,可以使用 hangUp 方法挂断通话。

client.getCallConnection(callConnectionId).hangUp(true);

运行代码

导航到包含 pom.xml 文件的目录并使用以下 mvn 命令:

  • 编译应用程序:mvn compile
  • 生成包:mvn package
  • 执行应用:mvn exec:java

先决条件

代码示例

GitHub 下载或克隆快速入门示例代码。

导航到 CallAutomation_OutboundCalling 文件夹并在代码编辑器中打开解决方案。

设置环境

下载示例代码并导航到项目目录,然后运行 npm 命令来安装必要的依赖项并设置开发者环境。

npm install

设置并托管 Azure DevTunnel

Azure DevTunnels 是一项 Azure 服务,可用于共享 Internet 上托管的本地 Web 服务。 使用 DevTunnel CLI 命令,将本地开发环境连接到公共 Internet。 我们使用此终结点通知你的应用程序来自 Azure 通信服务通话自动化服务的通话事件。

devtunnel create --allow-anonymous
devtunnel port create -p 8080
devtunnel host

更新应用程序配置

然后使用以下值更新 .env 文件:

  • CONNECTION_STRING:Azure 通信服务资源的连接字符串。 可以按照此处的说明查找 Azure 通信服务连接字符串。
  • CALLBACK_URI:初始化 DevTunnel 主机后,使用 URI 更新此字段。
  • TARGET_PHONE_NUMBER:使用你希望应用程序呼叫的电话号码更新此字段。 此电话号码应使用 E164 电话号码格式(例如 +18881234567)
  • ACS_RESOURCE_PHONE_NUMBER:使用获取的 Azure 通信服务电话号码更新此字段。 此电话号码应使用 E164 电话号码格式(例如 +18881234567)
  • COGNITIVE_SERVICES_ENDPOINT:使用 Azure AI 服务终结点更新字段。
  • TARGET_TEAMS_USER_ID:(可选)使用要添加到呼叫的 Microsoft Teams 用户 ID 来更新字段。 请参阅使用图形 API 获取 Teams 用户 ID
CONNECTION_STRING="<YOUR_CONNECTION_STRING>" 
ACS_RESOURCE_PHONE_NUMBER ="<YOUR_ACS_NUMBER>" 
TARGET_PHONE_NUMBER="<+1XXXXXXXXXX>" 
CALLBACK_URI="<VS_TUNNEL_URL>" 
COGNITIVE_SERVICES_ENDPOINT="<COGNITIVE_SERVICES_ENDPOINT>" 
TARGET_TEAMS_USER_ID="<TARGET_TEAMS_USER_ID>"

进行出站呼叫并播放媒体

若要从 Azure 通信服务进行出站呼叫,使用提供给环境的电话号码。 确保电话号码采用 E164 电话号码格式(例如 +18881234567)

以下代码使用提供的 target_phone_number 进行出站呼叫,并对该号码进行出站呼叫:

const callInvite: CallInvite = {
	targetParticipant: callee,
	sourceCallIdNumber: {
		phoneNumber: process.env.ACS_RESOURCE_PHONE_NUMBER || "",
	},
};

const options: CreateCallOptions = {
	cognitiveServicesEndpoint: process.env.COGNITIVE_SERVICES_ENDPOINT
};

console.log("Placing outbound call...");
acsClient.createCall(callInvite, process.env.CALLBACK_URI + "/api/callbacks", options);

(可选)将 Microsoft Teams 用户添加到呼叫

可以使用 addParticipant 方法通过 microsoftTeamsUserId 属性将 Microsoft Teams 用户添加到呼叫。 首先需要完成先决条件步骤“向 Azure 通信服务资源授权以允许呼叫 Microsoft Teams 用户”。 (可选)还可以传入 sourceDisplayName 来控制 Teams 用户的 Toast 通知中显示的文本。

await acsClient.getCallConnection(callConnectionId).addParticipant({
    targetParticipant: { microsoftTeamsUserId: process.env.TARGET_TEAMS_USER_ID },
    sourceDisplayName: "Jack (Contoso Tech Support)"
});

开始录制通话

通话自动化服务还支持开始录制和存储语音和视频通话的录制内容。 有关通话记录 API 的各种功能的详细信息,请参阅此处

const callLocator: CallLocator = {
    id: serverCallId,
    kind: "serverCallLocator",
};

const recordingOptions: StartRecordingOptions = {
    callLocator: callLocator,
};

const response = await acsClient.getCallRecording().start(recordingOptions);

recordingId = response.recordingId;

响应通话事件

在之前的应用程序中,我们已将 CALLBACK_URI 注册到通话自动化服务。 URI 指示服务要使用的终结点,以便通知我们发生的通话事件。 然后,我们可以循环访问事件并检测应用程序需要了解的特定事件。 我们响应事件以获取 CallConnected 通知并启动下游操作。 使用 TextSource,可以向服务提供想要合成并用于欢迎信息的文本。 Azure 通信服务通话自动化服务在发生 CallConnected 事件时播放此消息。

接下来,将该文本传递到 CallMediaRecognizeChoiceOptions,然后呼叫 StartRecognizingAsync。 这样应用程序就可以识别呼叫者选择的选项。

callConnectionId = eventData.callConnectionId;
serverCallId = eventData.serverCallId;
console.log("Call back event received, callConnectionId=%s, serverCallId=%s, eventType=%s", callConnectionId, serverCallId, event.type);
callConnection = acsClient.getCallConnection(callConnectionId);
const callMedia = callConnection.getCallMedia();

if (event.type === "Microsoft.Communication.CallConnected") {
 	console.log("Received CallConnected event");
 	await startRecording();
	await startRecognizing(callMedia, mainMenu, "");
}

async function startRecognizing(callMedia: CallMedia, textToPlay: string, context: string) {
	const playSource: TextSource = {
 		text: textToPlay,
 		voiceName: "en-US-NancyNeural",
 		kind: "textSource"
 	};

 	const recognizeOptions: CallMediaRecognizeChoiceOptions = {
 		choices: await getChoices(),
 		interruptPrompt: false,
 		initialSilenceTimeoutInSeconds: 10,
 		playPrompt: playSource,
 		operationContext: context,
 		kind: "callMediaRecognizeChoiceOptions"
 	};

 	await callMedia.startRecognizing(callee, recognizeOptions)
 }

处理选择事件

Azure 通信服务通话自动化会对已设置的 Webhook 触发 api/callbacks,并通知我们发生了 RecognizeCompleted 事件。 此事件使我们能够响应接收到的输入并触发操作。 然后,应用程序根据接收到的特定输入向呼叫者播放消息。

else if (event.type === "Microsoft.Communication.RecognizeCompleted") { 
	if(eventData.recognitionType === "choices"){ 
        	console.log("Recognition completed, event=%s, resultInformation=%s",eventData, eventData.resultInformation); 
        	var context = eventData.operationContext; 
            	const labelDetected = eventData.choiceResult.label;  
            	const phraseDetected = eventData.choiceResult.recognizedPhrase; 
            	console.log("Recognition completed, labelDetected=%s, phraseDetected=%s, context=%s", labelDetected, phraseDetected, eventData.operationContext); 
            	const textToPlay = labelDetected === confirmLabel ? confirmText : cancelText;            
            	await handlePlay(callMedia, textToPlay); 
        } 
}  
 
async function handlePlay(callConnectionMedia:CallMedia, textContent:string){ 
	const play : TextSource = { text:textContent , voiceName: "en-US-NancyNeural", kind: "textSource"} 
	await callConnectionMedia.playToAll([play]); 
} 

挂断呼叫

最后,当检测到需要终止通话的情况时,可以使用 hangUp() 方法挂断通话。

  await acsClient.getCallRecording().stop(recordingId);
  callConnection.hangUp(true);

运行代码

若要运行应用程序,请打开终端窗口并运行以下命令:

  npm run dev

先决条件

代码示例

GitHub 下载或克隆快速入门示例代码。

导航到 CallAutomation_OutboundCalling 文件夹并在代码编辑器中打开解决方案。

设置 Python 环境

使用以下命令创建和激活 python 环境并安装所需的包。 有关管理包的更多信息,请参阅此处

pip install -r requirements.txt

设置并托管 Azure DevTunnel

Azure DevTunnels 是一项 Azure 服务,可用于共享 Internet 上托管的本地 Web 服务。 使用以下命令,将本地开发环境连接到公共 Internet。 DevTunnel 会创建一个具有永久性终结点 URL 的隧道,可用于匿名访问。 我们使用此终结点通知你的应用程序来自 Azure 通信服务通话自动化服务的通话事件。

devtunnel create --allow-anonymous
devtunnel port create -p 8080
devtunnel host

更新应用程序配置

然后,使用以下值更新 main.py 文件:

  • ACS_CONNECTION_STRING:Azure 通信服务资源的连接字符串。 可以按照此处的说明查找 Azure 通信服务连接字符串。
  • CALLBACK_URI_HOST:初始化 DevTunnel 主机后,使用 URI 更新此字段。
  • TARGET_PHONE_NUMBER:使用你希望应用程序呼叫的电话号码更新此字段。 此电话号码应使用 E164 电话号码格式(例如 +18881234567)
  • ACS_PHONE_NUMBER:使用获取的 Azure 通信服务电话号码更新此字段。 此电话号码应使用 E164 电话号码格式(例如 +18881234567)
  • COGNITIVE_SERVICES_ENDPOINT:使用 Azure AI 服务终结点更新字段。
  • TARGET_TEAMS_USER_ID:(可选)使用要添加到呼叫的 Microsoft Teams 用户 ID 来更新字段。 请参阅使用图形 API 获取 Teams 用户 ID
# Your ACS resource connection string 
ACS_CONNECTION_STRING = "<ACS_CONNECTION_STRING>" 

# Your ACS resource phone number will act as source number to start outbound call 
ACS_PHONE_NUMBER = "<ACS_PHONE_NUMBER>" 

# Target phone number you want to receive the call. 
TARGET_PHONE_NUMBER = "<TARGET_PHONE_NUMBER>" 

# Callback events URI to handle callback events. 
CALLBACK_URI_HOST = "<CALLBACK_URI_HOST_WITH_PROTOCOL>" 
CALLBACK_EVENTS_URI = CALLBACK_URI_HOST + "/api/callbacks" 

#Your Cognitive service endpoint 
COGNITIVE_SERVICES_ENDPOINT = "<COGNITIVE_SERVICES_ENDPOINT>" 

#(OPTIONAL) Your target Microsoft Teams user Id ex. "ab01bc12-d457-4995-a27b-c405ecfe4870"
TARGET_TEAMS_USER_ID = "<TARGET_TEAMS_USER_ID>"

发起传出通话

若要从 Azure 通信服务进行出站呼叫,请先提供要接听电话的电话号码。 为简单起见,可以使用采用 E164电话号码格式(例如 +18881234567)的电话号码更新 target_phone_number

使用提供的 target_phone_number 进行出站呼叫:

target_participant = PhoneNumberIdentifier(TARGET_PHONE_NUMBER) 
source_caller = PhoneNumberIdentifier(ACS_PHONE_NUMBER) 
call_invite = CallInvite(target=target_participant, source_caller_id_number=source_caller) 
call_connection_properties = call_automation_client.create_call(call_invite, CALLBACK_EVENTS_URI, 
cognitive_services_endpoint=COGNITIVE_SERVICES_ENDPOINT) 
    app.logger.info("Created call with connection id: %s",
call_connection_properties.call_connection_id) 
return redirect("/") 

(可选)将 Microsoft Teams 用户添加到呼叫

可以使用 add_participant 方法通过 MicrosoftTeamsUserIdentifier 和 Teams 用户 ID 将 Microsoft Teams 用户添加到呼叫。首先需要完成先决条件步骤“向 Azure 通信服务资源授权以允许呼叫 Microsoft Teams 用户”。 (可选)还可以传入 source_display_name 来控制 Teams 用户的 Toast 通知中显示的文本。

call_connection_client.add_participant(target_participant = CallInvite(
    target = MicrosoftTeamsUserIdentifier(user_id=TARGET_TEAMS_USER_ID),
    source_display_name = "Jack (Contoso Tech Support)"))

开始录制通话

通话自动化服务还支持开始录制和存储语音和视频通话的录制内容。 有关通话记录 API 的各种功能的详细信息,请参阅此处

recording_properties = call_automation_client.start_recording(ServerCallLocator(event.data['serverCallId']))
recording_id = recording_properties.recording_id

响应通话事件

在之前的应用程序中,我们已将 CALLBACK_URI_HOST 注册到通话自动化服务。 URI 指示服务要使用的终结点,以便通知我们发生的通话事件。 然后,我们可以循环访问事件并检测应用程序需要了解的特定事件。 下面的代码响应 CallConnected 事件。

@app.route('/api/callbacks', methods=['POST'])
def callback_events_handler():
    for event_dict in request.json:
        event = CloudEvent.from_dict(event_dict)
        if event.type == "Microsoft.Communication.CallConnected":
            # Handle Call Connected Event
            ...
            return Response(status=200)

播放欢迎消息并识别身份

使用 TextSource,可以向服务提供想要合成并用于欢迎信息的文本。 Azure 通信服务通话自动化服务在发生 CallConnected 事件时播放此消息。

接下来,将该文本传递到 CallMediaRecognizeChoiceOptions,然后呼叫 StartRecognizingAsync。 这样应用程序就可以识别呼叫者选择的选项。


get_media_recognize_choice_options( 
    call_connection_client=call_connection_client, 
    text_to_play=MainMenu,  
    target_participant=target_participant, 
    choices=get_choices(),context="") 

def get_media_recognize_choice_options(call_connection_client: CallConnectionClient, text_to_play: str, target_participant:str, choices: any, context: str): 
    play_source =  TextSource (text= text_to_play, voice_name= SpeechToTextVoice) 
    call_connection_client.start_recognizing_media( 
        input_type=RecognizeInputType.CHOICES, 

        target_participant=target_participant,
        choices=choices, 
        play_prompt=play_source, 
        interrupt_prompt=False, 
        initial_silence_timeout=10, 
        operation_context=context 
    ) 

def get_choices(): 
    choices = [ 
        RecognitionChoice(label = ConfirmChoiceLabel, phrases= ["Confirm", "First", "One"], tone = DtmfTone.ONE), 
        RecognitionChoice(label = CancelChoiceLabel, phrases= ["Cancel", "Second", "Two"], tone = DtmfTone.TWO) 
    ] 
return choices 

处理选择事件

Azure 通信服务通话自动化会对已设置的 Webhook 触发 api/callbacks,并通知我们发生了 RecognizeCompleted 事件。 此事件使我们能够响应接收到的输入并触发操作。 然后,应用程序根据接收到的特定输入向呼叫者播放消息。

elif event.type == "Microsoft.Communication.RecognizeCompleted":
	app.logger.info("Recognize completed: data=%s", event.data)
if event.data['recognitionType'] == "choices":
	labelDetected = event.data['choiceResult']['label'];
phraseDetected = event.data['choiceResult']['recognizedPhrase'];
app.logger.info("Recognition completed, labelDetected=%s, phraseDetected=%s, context=%s", labelDetected, phraseDetected, event.data.get('operationContext'))
if labelDetected == ConfirmChoiceLabel:
	textToPlay = ConfirmedText
else:
	textToPlay = CancelText
handle_play(call_connection_client = call_connection_client, text_to_play = textToPlay)
def handle_play(call_connection_client: CallConnectionClient, text_to_play: str):
	play_source = TextSource(text = text_to_play, voice_name = SpeechToTextVoice)
call_connection_client.play_media_to_all(play_source)

挂断呼叫

最后,当检测到需要终止通话的情况时,可以使用 hang_up() 方法挂断通话。 最后,还可以安全地停止通话录制操作。

call_automation_client.stop_recording(recording_id)
call_connection_client.hang_up(is_for_everyone=True)

运行代码

若要使用 VS Code 运行应用程序,请打开终端窗口并运行以下命令

python main.py