다음을 통해 공유


빠른 시작: 통화 앱에 선택 자막 추가

필수 조건

참고 항목

이 가이드에 설명된 선택 자막 기능에 액세스하려면 Azure Communication Services 통화 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 prop이 포함되어 있습니다. 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 사용자가 통화에 참가하거나 통화가 interop 호출 유형으로 변경되는 경우 캡션 종류가 캡션에서 TeamsCaptions로 변경됩니다. 캡션 환경을 계속하려면 Teams 캡션 수신기에 다시 제출해야 합니다. TeamsCaptions를 호출에서 활용한 후에는 TeamsCaptions 종류를 호출에서 캡션 종류로 전환하거나 다시 변경할 수 없습니다.

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

필수 조건

참고 항목

이 가이드에 설명된 선택 자막 기능에 액세스하려면 Azure Communication Services 통화 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 전용 호출에 초대할 TeamsCaptions 때 캡션 유형이 변경 CommunicationCaptions 될 때 트리거됩니다.

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 Communication Services 통화 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 전용 호출에 초대할 TeamsCaptions 때 캡션 유형이 변경 CommunicationCaptions 될 때 트리거됩니다.

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 Communication Services 통화 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
            }
        }
    }
}

수신기 구독

수신기를 추가하여 사용/사용 안 함, 형식, 음성 언어, 캡션 언어 상태 변경 및 수신된 데이터 수신

이 이벤트는 didChangeActiveCaptionsType MICROSOFT 365 사용자를 ACS 전용 호출에 초대할 TeamsCaptions 때 캡션 유형이 변경 CommunicationCaptions 될 때 트리거됩니다.

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 {
        }
    })
}

정리

여기에서 리소스 정리에 대해 자세히 알아보세요.

리소스 정리

Communication Services 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제하면 됩니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다. 리소스 정리에 대해 자세히 알아보세요.

다음 단계

자세한 내용은 다음 문서를 참조하세요.