快速入門:使用通話自動化進行撥出通話

Azure 通訊服務呼叫自動化 API 是建立互動式呼叫體驗的強大方式。 在本快速入門中,我們會討論如何進行輸出通話,並辨識通話中的各種事件。

必要條件

範例指令碼

GitHub 下載或複製快速入門範例程式代碼。

瀏覽至 CallAutomation_OutboundCalling 資料夾,並在程式碼編輯器中開啟方案。

設定及裝載您的 Azure DevTunnel

Azure DevTunnels 是一項 Azure 服務,可讓您共用裝載在因特網上的本機 Web 服務。 執行命令,將本機開發環境連線到公用因特網。 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 用戶標識符。 請參閱 使用圖形 API 來取得 Teams 用戶識別碼
// 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 使用者新增至通話

您可以使用 方法搭配 MicrosoftTeamsUserIdentifier 和 Teams 使用者的識別碼,將 Microsoft Teams 使用者新增至呼叫AddParticipantAsync。您必須先完成 Azure 通訊服務 資源的必要步驟授權,才能呼叫 Microsoft Teams 使用者。 您也可以選擇性地傳入 SourceDisplayName ,以控制 Teams 使用者快顯通知中顯示的文字。

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 通訊服務呼叫自動化會api/callbacks觸發我們設定的 Webhook,並將通知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 服務,可讓您共用裝載在因特網上的本機 Web 服務。 執行DevTunnel命令,將本機開發環境連線到公用因特網。 DevTunnels 接著會建立具有永續性端點 URL 的通道,並允許匿名存取。 Azure 通訊服務 使用此端點來通知您的應用程式從 Azure 通訊服務 通話自動化服務呼叫事件。

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

更新您的應用程式組態

然後開啟 application.yml 資料夾中的 /resources 檔案,以設定下列值:

  • connectionstring:Azure 通訊服務 資源的 連接字串。 您可以使用這裡的指示找到您的 Azure 通訊服務 連接字串。
  • basecallbackuri:一旦您的 DevTunnel 主機初始化之後,請使用該 URI 更新此欄位。
  • callerphonenumber:使用您取得的 Azure 通訊服務 電話號碼來更新此欄位。 此電話號碼應使用 E164 電話號碼格式(例如 +18881234567)
  • targetphonenumber:使用您希望應用程式撥打的電話號碼來更新欄位。 此電話號碼應使用 E164 電話號碼格式(例如 +18881234567)
  • cognitiveServiceEndpoint:使用您的 Azure AI 服務端點更新欄位。
  • targetTeamsUserId:[選擇性] 更新字段,其中包含您想要新增至通話的 Microsoft Teams 用戶標識符。 請參閱 使用圖形 API 來取得 Teams 用戶識別碼
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 通訊服務 進行輸出呼叫,此範例會使用targetphonenumber您在 檔案中application.yml定義的 ,使用 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 使用者新增至通話

您可以使用 方法搭配 MicrosoftTeamsUserIdentifier 和 Teams 使用者的識別碼,將 Microsoft Teams 使用者新增至呼叫addParticipant。您必須先完成 Azure 通訊服務 資源的必要步驟授權,才能呼叫 Microsoft Teams 使用者。 您也可以選擇性地傳入 SourceDisplayName ,以控制 Teams 使用者快顯通知中顯示的文字。

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 通訊服務呼叫自動化會api/callbacks觸發我們設定的 Webhook,並將通知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 服務,可讓您共用裝載在因特網上的本機 Web 服務。 使用 DevTunnel CLI 命令,將本機開發環境連線到公用因特網。 我們會使用此端點來通知您的應用程式從 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 用戶標識符。 請參閱 使用圖形 API 來取得 Teams 用戶識別碼
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 使用者新增至通話

您可以使用 方法搭配 microsoftTeamsUserId 屬性,將 Microsoft Teams 使用者新增至呼叫addParticipant。 您必須先完成 Azure 通訊服務 資源的必要步驟授權,才能呼叫 Microsoft Teams 使用者。 您也可以選擇性地傳入 sourceDisplayName ,以控制 Teams 使用者快顯通知中顯示的文字。

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 通訊服務呼叫自動化會api/callbacks觸發我們設定的 Webhook,並將通知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 服務,可讓您共用裝載在因特網上的本機 Web 服務。 使用 命令將本機開發環境連線到公用因特網。 DevTunnels 會建立具有永續性端點 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 用戶標識符。 請參閱 使用圖形 API 來取得 Teams 用戶識別碼
# 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 電話號碼格式的電話號碼來更新 target_phone_number (例如 +18881234567)

使用您提供的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 使用者新增至通話

您可以使用 方法搭配 MicrosoftTeamsUserIdentifier 和 Teams 使用者的識別碼,將 Microsoft Teams 使用者新增至呼叫add_participant。您必須先完成 Azure 通訊服務 資源的必要步驟授權,才能呼叫 Microsoft Teams 使用者。 您也可以選擇性地傳入 source_display_name ,以控制 Teams 使用者快顯通知中顯示的文字。

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 通訊服務呼叫自動化會api/callbacks觸發我們設定的 Webhook,並將通知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