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

快速入门:将隐藏式字幕添加到呼叫应用

先决条件

注意

请注意,你需要具有使用 Azure 通信服务通话 SDK 进行语音通话的应用,以访问本指南中所述的隐藏式字幕功能。

模型

名称 说明
CaptionsCallFeature 字幕的 API
CaptionsCommon 字幕的基类
StartCaptionOptions 隐藏式字幕选项,如口语
CaptionsHandler 用于处理 CaptionsReceivedEventType 事件的回叫定义
CaptionsInfo 为每个 CaptionsReceivedEventType 事件接收的数据结构

获取隐藏式字幕功能

let captionsCallFeature: SDK.CaptionsCallFeature = call.feature(SDK.Features.Captions);

获取字幕对象

需要获取和强制转换字幕对象,才能利用字幕特定功能。

let captions: SDK.Captions;
if (captionsCallFeature.captions.kind === 'Captions') {
    captions = captionsCallFeature.captions as SDK.Captions;
}

订阅侦听器

添加侦听器以接收字幕活动/非活动状态

const captionsActiveChangedHandler = () => {
    if (captions.isCaptionsFeatureActive) {
        /* USER CODE HERE - E.G. RENDER TO DOM */
    }
}
captions.on('CaptionsActiveChanged', captionsActiveChangedHandler);

为收到的字幕数据添加侦听器

处理返回的 CaptionsInfo 数据对象。

注意:该对象包含一个 resultType 属性,用于指示数据是部分字幕还是最终版本的字幕。 ResultType Partial 指示未经编辑的实时字幕,而 Final 指示句子的最终解释版本(即包括标点和大写)。

const captionsReceivedHandler : CaptionsHandler = (data: CaptionsInfo) => { 
    /** USER CODE HERE - E.G. RENDER TO DOM 
     * data.resultType
     * data.speaker
     * data.spokenLanguage
     * data.spokenText
     * data.timeStamp
    */
   // Example code:
   // Create a dom element, i.e. div, with id "captionArea" before proceeding with the sample code
    let mri: string;
    switch (data.speaker.identifier.kind) {
        case 'communicationUser': { mri = data.speaker.identifier.communicationUserId; break; }
        case 'phoneNumber': { mri = data.speaker.identifier.phoneNumber; break; }
    }
    const outgoingCaption = `prefix${mri.replace(/:/g, '').replace(/-/g, '')}`;

    let captionArea = document.getElementById("captionArea");
    const captionText = `${data.timestamp.toUTCString()}
        ${data.speaker.displayName}: ${data.spokenText}`;

    let foundCaptionContainer = captionArea.querySelector(`.${outgoingCaption}[isNotFinal='true']`);
    if (!foundCaptionContainer) {
        let captionContainer = document.createElement('div');
        captionContainer.setAttribute('isNotFinal', 'true');
        captionContainer.style['borderBottom'] = '1px solid';
        captionContainer.style['whiteSpace'] = 'pre-line';
        captionContainer.textContent = captionText;
        captionContainer.classList.add(outgoingCaption);

        captionArea.appendChild(captionContainer);
    } else {
        foundCaptionContainer.textContent = captionText;

        if (captionData.resultType === 'Final') {
            foundCaptionContainer.setAttribute('isNotFinal', 'false');
        }
    }
}; 
captions.on('CaptionsReceived', captionsReceivedHandler); 

添加侦听器以接收口语更改后的状态

// set a local variable currentSpokenLanguage to track the current spoken language in the call
let currentSpokenLanguage = ''
const spokenLanguageChangedHandler = () => {
    if (captions.activeSpokenLanguage !== currentSpokenLanguage) {
        /* USER CODE HERE - E.G. RENDER TO DOM */
    }
}
captions.on('SpokenLanguageChanged', spokenLanguageChangedHandler)

开始字幕

设置所有侦听器后,现在可以开始添加字幕。

try {
    await captions.startCaptions({ spokenLanguage: 'en-us' });
} catch (e) {
    /* USER ERROR HANDLING CODE HERE */
}

停止字幕

try {
    captions.stopCaptions(); 
} catch (e) {
    /* USER ERROR HANDLING CODE HERE */
}

取消订阅侦听器

captions.off('CaptionsActiveChanged', captionsActiveChangedHandler);
captions.off('CaptionsReceived', captionsReceivedHandler); 

口语支持

获取支持的口语列表

获取启用隐藏式字幕时用户可以选择的受支持口语的列表。 该属性以 bcp 47 格式返回语言数组。

const spokenLanguages = captions.supportedSpokenLanguages; 

设置口语

从支持的口语数组传入一个值,确保支持所请求的语言。 默认情况下,如果 contoso 未提供任何语言或提供的语言不受支持,则口语默认为“en-us”。

// bcp 47 formatted language code
const language = 'en-us'; 

// Alternatively, pass a value from the supported spoken languages array
const language = spokenLanguages[0]; 

try {
    captions.setSpokenLanguage(language);
} catch (e) {
    /* USER ERROR HANDLING CODE HERE */
}

添加侦听器以接收字幕类型已更改状态

如果 Teams/CTE 用户加入通话或通话更改为互操作通话类型,则字幕类型可能会从 Captions 更改为 TeamsCaptions。 需要重新订阅 Teams 字幕侦听器才能继续使用字幕体验。 在通话中使用 TeamsCaptions 后,TeamsCaptions 类型不能切换或更改回 Captions 类型。

const captionsKindChangedHandler = () => {
    /* USER CODE HERE - E.G. SUBSCRIBE TO TEAMS CAPTIONS */
}
captions.on('CaptionsKindChanged', captionsKindChangedHandler)

先决条件

注意

请注意,你需要具有使用 Azure 通信服务通话 SDK 进行语音通话的应用,以访问本指南中所述的隐藏式字幕功能。

模型

名称 说明
CaptionsCallFeature 用于字幕调用功能的 API
CommunicationCaptions 用于通信字幕的 API
StartCaptionOptions 隐藏式字幕选项,如口语
CommunicationCaptionsReceivedEventArgs 为每个通信字幕接收事件接收的数据对象

获取隐藏式字幕功能

需要获取和强制转换字幕对象,才能利用字幕特定功能。

CaptionsCallFeature captionsCallFeature = call.Features.Captions;
CallCaptions callCaptions = await captionsCallFeature.GetCaptionsAsync();
if (callCaptions.CaptionsKind == CaptionsKind.CommunicationCaptions)
{
    CommunicationCaptions communicationCaptions = callCaptions as CommunicationCaptions;
} 

订阅侦听器

添加侦听器以接收已启用/禁用字幕状态

communicationCaptions.CaptionsEnabledChanged += OnIsCaptionsEnabledChanged;

private void OnIsCaptionsEnabledChanged(object sender, PropertyChangedEventArgs args)
{
    if (communicationCaptions.IsEnabled)
    {
    }
}

添加侦听器以接收已更改的字幕类型

如果字幕类型在邀请 Microsoft 365 用户进行仅限 ACS 的呼叫时从 CommunicationCaptions 更改为 TeamsCaptions,则将触发此事件。

captionsCallFeature.ActiveCaptionsTypeChanged += OnIsCaptionsTypeChanged;

private void OnIsCaptionsTypeChanged(object sender, PropertyChangedEventArgs args)
{
    // get captions
}

为收到的字幕数据添加侦听器

communicationCaptions.CaptionsReceived += OnCaptionsReceived;

private void OnCaptionsReceived(object sender, CommunicationCaptionsReceivedEventArgs eventArgs)
{
    // Information about the speaker.
    // eventArgs.Speaker
    // The original text with no transcribed.
    // eventArgs.SpokenText
    // language identifier for the speaker.
    // eventArgs.SpokenLanguage
    // Timestamp denoting the time when the corresponding speech was made.
    // eventArgs.Timestamp
    // CaptionsResultKind is Partial if text contains partially spoken sentence.
    // It is set to Final once the sentence has been completely transcribed.
    // eventArgs.ResultKind
}

添加侦听器以接收主动口语更改状态

communicationCaptions.ActiveSpokenLanguageChanged += OnIsActiveSpokenLanguageChanged;

private void OnIsActiveSpokenLanguageChanged(object sender, PropertyChangedEventArgs args)
{
    // communicationCaptions.ActiveSpokenLanguage
}

开始字幕

设置所有侦听器后,现在可以开始添加字幕。


private async void StartCaptions()
{
    var options = new StartCaptionsOptions
    {
        SpokenLanguage = "en-us"
    };
    try
    {
        await communicationCaptions.StartCaptionsAsync(options);
    }
    catch (Exception ex)
    {
    }
}

停止字幕

private async void StopCaptions()
{
    try
    {
        await communicationCaptions.StopCaptionsAsync();
    }
    catch (Exception ex)
    {
    }
}

移除字幕接收侦听器

communicationCaptions.CaptionsReceived -= OnCaptionsReceived;

口语支持

获取支持的口语列表

获取启用隐藏式字幕时用户可以选择的受支持口语的列表。

// bcp 47 formatted language code
IReadOnlyList<string> sLanguages = communicationCaptions.SupportedSpokenLanguages;```

### Set spoken language 
When the user selects the spoken language, your app can set the spoken language that it expects captions to be generated from. 

``` cs 
public async void SetSpokenLanguage()
{
    try
    {
        await communicationCaptions.SetSpokenLanguageAsync("en-us");
    }
    catch (Exception ex)
    {
    }
}

清理

参阅此处了解清理资源的更多详细信息。

先决条件

注意

请注意,你需要具有使用 Azure 通信服务通话 SDK 进行语音通话的应用,以访问本指南中所述的隐藏式字幕功能。

模型

名称 说明
CaptionsCallFeature 用于字幕调用功能的 API
CommunicationCaptions 用于通信字幕的 API
StartCaptionOptions 隐藏式字幕选项,如口语
CommunicationCaptionsListener CommunicationCaptions addOnCaptionsReceivedListener 的侦听器
CommunicationCaptionsReceivedEvent 为每个 CommunicationCaptionsListener 事件接收的数据对象

获取隐藏式字幕功能

需要获取和强制转换字幕对象,才能利用字幕特定功能。

CaptionsCallFeature captionsCallFeature = call.feature(Features.CAPTIONS);
captionsCallFeature.getCaptions().whenComplete(
    ((captions, throwable) -> {
        if (throwable == null) {
            CallCaptions callCaptions = captions;
            if (captions.getCaptionsType() == CaptionsType.COMMUNICATION_CAPTIONS) {
            // communication captions
            CommunicationCaptions communicationCaptions = (CommunicationCaptions) captions;
            }
        } else {
        // get captions failed
        // throwable is the exception/cause
        }
    }));

订阅侦听器

添加侦听器以接收已启用/禁用字幕状态

public void addOnIsCaptionsEnabledChangedListener() {
    communicationCaptions.addOnCaptionsEnabledChangedListener( (PropertyChangedEvent args) -> {
        if(communicationCaptions.isEnabled()) {
            // captions enabled
        }
    });
}

添加侦听器以接收已更改的字幕类型

如果字幕类型在邀请 Microsoft 365 用户进行仅限 ACS 的呼叫时从 CommunicationCaptions 更改为 TeamsCaptions,则将触发此事件。

public void addOnIsCaptionsTypeChangedListener() {
    captionsCallFeature.addOnActiveCaptionsTypeChangedListener( (PropertyChangedEvent args) -> {
        if(communicationCaptions.isEnabled()) {
            // captionsCallFeature.getCaptions();
        }
    });
}

为收到的字幕数据添加侦听器

CommunicationCaptionsListener captionsListener = (CommunicationCaptionsReceivedEvent args) -> {
  // Information about the speaker.
  // CallerInfo participantInfo = args.getSpeaker();
  // The original text with no transcribed.
  // args.getSpokenText();
  // language identifier for the speaker.
  // args.getSpokenLanguage();
  // Timestamp denoting the time when the corresponding speech was made.
  // args.getTimestamp();
  // CaptionsResultType is Partial if text contains partially spoken sentence.
  // It is set to Final once the sentence has been completely transcribed.
  // args.getResultType() == CaptionsResultType.FINAL;
}; 
public void addOnCaptionsReceivedListener() {
  communicationCaptions.addOnCaptionsReceivedListener(captionsListener); 
}

添加侦听器以接收主动口语更改状态

public void addOnActiveSpokenLanguageChangedListener() {
    communicationCaptions.addOnActiveSpokenLanguageChangedListener( (PropertyChangedEvent args) -> {
       // communicationCaptions.getActiveSpokenLanguage()
    });
}

开始字幕

设置所有侦听器后,现在可以开始添加字幕。

public void startCaptions() {
    StartCaptionsOptions startCaptionsOptions = new StartCaptionsOptions();
    startCaptionsOptions.setSpokenLanguage("en-us");
    communicationCaptions.startCaptions(startCaptionsOptions).whenComplete((result, error) -> {
        if (error != null) {
        }
    });
}

停止字幕

public void stopCaptions() {
    communicationCaptions.stopCaptions().whenComplete((result, error) -> {
        if (error != null) {
        }
    });
}

移除字幕接收侦听器

public void removeOnCaptionsReceivedListener() {
    communicationCaptions.removeOnCaptionsReceivedListener(captionsListener);
}

口语支持

获取支持的口语列表

获取启用隐藏式字幕时用户可以选择的受支持口语的列表。

// bcp 47 formatted language code
communicationCaptions.getSupportedSpokenLanguages();

设置口语

当用户选择口语时,你的应用可以设置它期望用于生成字幕的口语。

public void setSpokenLanguage() {
    communicationCaptions.setSpokenLanguage("en-us").whenComplete((result, error) -> {
        if (error != null) {
        }
    });
}

清理

参阅此处了解清理资源的更多详细信息。

先决条件

注意

请注意,你需要具有使用 Azure 通信服务通话 SDK 进行语音通话的应用,以访问本指南中所述的隐藏式字幕功能。

模型

名称 说明
CaptionsCallFeature 用于字幕调用功能的 API
CommunicationCaptions 用于通信字幕的 API
StartCaptionOptions 隐藏式字幕选项,如口语
CommunicationCaptionsDelegate 通信字幕的代理
CommunicationCaptionsReceivedEventArgs 为每个通信字幕接收事件接收的数据对象

获取隐藏式字幕功能

需要获取和强制转换字幕对象,才能利用字幕特定功能。

if let call = self.call {
    @State var captionsCallFeature = call.feature(Features.captions)
    captionsCallFeature.getCaptions{(value, error) in
        if let error = error {
            // failed to get captions
        } else {
            if (value?.type == CaptionsType.communicationCaptions) {
                // communication captions
                @State var communicationCaptions = value as? CommunicationCaptions
            }
        }
    }
}

订阅侦听器

添加侦听器以接收已启用/禁用字幕、类型、口语、字幕语言状态更改以及数据接收

如果字幕类型在邀请 Microsoft 365 用户进行仅限 ACS 的呼叫时从 CommunicationCaptions 更改为 TeamsCaptions,则将触发事件 didChangeActiveCaptionsType

extension CallObserver: CommunicationCaptionsDelegate {
    // listener for receive captions enabled/disabled status
    public func communicationCaptions(_ communicationCaptions: CommunicationCaptions, didChangeCaptionsEnabledState args: PropertyChangedEventArgs) {
        // communicationCaptions.isEnabled
    }
    
    // listener for active spoken language state change
    public func communicationCaptions(_ communicationCaptions: CommunicationCaptions, didChangeActiveSpokenLanguageState args: PropertyChangedEventArgs) {
        // communicationCaptions.activeSpokenLanguage
    }
    
    // listener for captions data received
    public func communicationCaptions(_ communicationCaptions: CommunicationCaptions, didReceiveCaptions:CommunicationCaptionsReceivedEventArgs) {
            // Information about the speaker.
            // didReceiveCaptions.speaker
            // The original text with no transcribed.
            // didReceiveCaptions.spokenText
            // language identifier for the speaker.
            // didReceiveCaptions.spokenLanguage
            // Timestamp denoting the time when the corresponding speech was made.
            // didReceiveCaptions.timestamp
            // CaptionsResultType is Partial if text contains partially spoken sentence.
            // It is set to Final once the sentence has been completely transcribed.
            // didReceiveCaptions.resultType
    }
}

communicationCaptions.delegate = self.callObserver

extension CallObserver: CaptionsCallFeatureDelegate {
    // captions type changed
    public func captionsCallFeature(_ captionsCallFeature: CaptionsCallFeature, didChangeActiveCaptionsType args: PropertyChangedEventArgs) {
        // captionsCallFeature.getCaptions to get captions
    }
}

captionsCallFeature.delegate = self.callObserver

开始字幕

设置所有侦听器后,现在可以开始添加字幕。

func startCaptions() {
    guard let communicationCaptions = communicationCaptions else {
        return
    }
    let startCaptionsOptions = StartCaptionsOptions()
    startCaptionsOptions.spokenLanguage = "en-us"
    communicationCaptions.startCaptions(startCaptionsOptions: startCaptionsOptions, completionHandler: { (error) in
        if error != nil {
            
        }
    })
}

停止字幕

func stopCaptions() {
    communicationCaptions.stopCaptions(completionHandler: { (error) in
        if error != nil {
            
        }
    })
}

移除字幕接收侦听器

communicationCaptions?.delegate = nil

口语支持

获取支持的口语列表

获取启用隐藏式字幕时用户可以选择的受支持口语的列表。

// bcp 47 formatted language code
let spokenLanguage : String = "en-us"
for language in communicationCaptions?.supportedSpokenLanguages ?? [] {
    // choose required language
    spokenLanguage = language
}

设置口语

当用户选择口语时,你的应用可以设置它期望用于生成字幕的口语。

func setSpokenLanguage() {
    guard let communicationCaptions = self.communicationCaptions else {
        return
    }

    communicationCaptions.set(spokenLanguage: spokenLanguage, completionHandler: { (error) in
        if let error = error {
        }
    })
}

清理

参阅此处了解清理资源的更多详细信息。

清理资源

如果想要清理并删除通信服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。 了解有关清理资源的详细信息。

后续步骤

有关详细信息,请参阅以下文章: