Compartir vía


Habilitar subtítulos para la interoperabilidad de Teams

Aprenda a permitir que los usuarios habiliten subtítulos durante un escenario de interoperabilidad de Teams en el que los usuarios puedan estar en reunión entre un usuario de Azure Communication Services y un usuario cliente de Teams, o dónde usan el SDK de llamadas de Azure Communication Services con su identidad de Microsoft 365.

Requisitos previos

Nota:

Tenga en cuenta que deberá tener una aplicación de llamada de voz con el uso de los SDK de llamada de Azure Communication Services para acceder a la característica de subtítulos que se describe en esta guía.

Modelos

Nombre Descripción
CaptionsCallFeature API para la característica de llamada de subtítulos
TeamsCaptions API para subtítulos de Teams
StartCaptionOptions Opciones de subtítulos como idioma hablado
TeamsCaptionsReceivedEventArgs Objeto de datos recibido para cada evento recibido de subtítulos de Teams

Obtener característica de subtítulos

Usuarios de identidad externa y usuarios de Microsoft 365

Si va a crear una aplicación que permita a los usuarios de Azure Communication Services unirse a una reunión de Teams

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

Suscribirse a agentes de escucha

Agregar un agente de escucha para recibir el estado habilitado o deshabilitado de los subtítulos

teamsCaptions.CaptionsEnabledChanged += OnIsCaptionsEnabledChanged;

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

Agregar agente de escucha para los datos de subtítulos recibidos

teamsCaptions.CaptionsReceived += OnCaptionsReceived;

private void OnCaptionsReceived(object sender, TeamsCaptionsReceivedEventArgs eventArgs)
{
    // Information about the speaker.
    // eventArgs.Speaker
    // The original text with no transcribed.
    // eventArgs.SpokenText
    // language identifier for the captions text.
    // eventArgs.CaptionLanguage
    // language identifier for the speaker.
    // eventArgs.SpokenLanguage
    // The transcribed text.
    // eventArgs.CaptionText
    // 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
}

Agregar un agente de escucha para recibir el estado de cambio de idioma hablado activo

teamsCaptions.ActiveSpokenLanguageChanged += OnIsActiveSpokenLanguageChanged;

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

Agregar un agente de escucha para recibir el estado del idioma del título activo cambiado

teamsCaptions.ActiveCaptionLanguageChanged += OnIsActiveCaptionLanguageChanged;

private void OnIsActiveCaptionLanguageChanged(object sender, PropertyChangedEventArgs args)
{
    // teamsCaptions.ActiveCaptionLanguage
}

Inicio de subtítulos

Una vez configurados todos los agentes de escucha, ahora puede empezar a agregar subtítulos.


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

Detener subtítulos

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

Quitar el agente de escucha recibido de subtítulos

teamsCaptions.CaptionsReceived -= OnCaptionsReceived;

Compatibilidad con idiomas hablados

Obtener lista de idiomas hablados admitidos

Obtenga una lista de los idiomas hablados admitidos entre los que los usuarios pueden seleccionar al habilitar subtítulos.

// bcp 47 formatted language code
IReadOnlyList<string> sLanguages = teamsCaptions.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 teamsCaptions.SetSpokenLanguageAsync("en-us");
    }
    catch (Exception ex)
    {
    }
}

Compatibilidad con idiomas de subtítulos

Obtener el idioma del subtítulo admitido

Si su organización tiene una licencia Premium de Teams activa, los usuarios de Azure Communication Services pueden habilitar subtítulos traducidos siempre que el organizador de la reunión tenga una licencia Teams Premium. En cuanto a los usuarios con identidades de Microsoft 365, esta comprobación se realiza en su propia cuenta de usuario si el organizador de reuniones no tiene una licencia Teams Premium.

// ISO 639-1 formatted language code
IReadOnlyList<string> cLanguages = teamsCaptions.SupportedCaptionLanguages;

Establecer idioma del subtítulo

public async void SetCaptionLanguage()
{
    try
    {
        await teamsCaptions.SetCaptionLanguageAsync("en");
    }
    catch (Exception ex)
    {
    }
}

Requisitos previos

Nota:

Tenga en cuenta que deberá tener una aplicación de llamada de voz con el uso de los SDK de llamada de Azure Communication Services para acceder a la característica de subtítulos que se describe en esta guía.

Modelos

Nombre Descripción
CaptionsCallFeature API para subtítulos
CaptionsCommon Clase base para subtítulos
StartCaptionOptions Opciones de subtítulos como idioma hablado
TeamsCaptionHandler Definición de devolución de llamada para controlar el evento CaptionsReceivedEventType
TeamsCaptionsInfo Estructura de datos recibida para cada evento CaptionsReceivedEventType

Obtener característica de subtítulos

Usuarios de identidad externa

Si va a crear una aplicación que permita a los usuarios de Azure Communication Services unirse a una reunión de Teams.

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

Usuarios de Microsoft 365

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

Obtener objeto de subtítulos de Teams

Debe obtener y convertir el objeto Subtítulos de Teams para usar características específicas de los subtítulos de Teams

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

Suscribirse a agentes de escucha

Agregar un agente de escucha para recibir el estado activo o inactivo de los subtítulos

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

Agregar un agente de escucha para los datos de subtítulos recibidos

Controle el objeto de datos TeamsCaptionsInfo devuelto.

Nota: El objeto contiene una propiedad resultType que indica si los datos son un subtítulo parcial o una versión finalizada del subtítulo. ResultType partial indica un subtítulo sin editar activo, mientras que final indica una versión interpretada finalizada de la oración (es decir, incluye signos de puntuación y mayúsculas).

let currentCaptionLanguage : string;
const captionsReceivedHandler : TeamsCaptionsHandler = (data: TeamsCaptionsInfo) => { 
    /** USER CODE HERE - E.G. RENDER TO DOM 
     * data.captionLanguage
     * data.captionText
     * data.resultType
     * data.speaker
     * data.spokenText
     * data.timeStamp
    */
   // Example code:
   // Create a dom element, i.e. div, with id "captionArea" before proceeding with the sample code
    if (!this._currentCaptionLanguage || this._currentCaptionLanguage === data.captionLanguage) {
        let mri: string;
        switch (data.speaker.identifier.kind) {
            case 'communicationUser': { mri = data.speaker.identifier.communicationUserId; break; }
            case 'microsoftTeamsUser': { mri = data.speaker.identifier.microsoftTeamsUserId; 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.captionText ?? 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(newClassName);

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

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

Agregar un agente de escucha para recibir el estado de cambio de idioma hablado

const spokenLanguageChangedHandler = () => {
    if (teamsCaptions.activeSpokenLanguage !== currentSpokenLanguage) {
        /* USER CODE HERE - E.G. RENDER TO DOM */
    }
}
teamsCaptions.on('SpokenLanguageChanged', spokenLanguageChangedHandler)

Agregar un agente de escucha para recibir el estado de cambio de idioma del subtítulo

const captionLanguageChangedHandler = () => {
    if (teamsCaptions.activeCaptionLanguage !== currentCaptionLanguage) {
        /* USER CODE HERE - E.G. RENDER TO DOM */
    }
}
teamsCaptions.on('CaptionLanguageChanged', captionLanguageChangedHandler)

Inicio de subtítulos

Una vez configurados todos los agentes de escucha, ahora puede empezar a agregar subtítulos.

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

Detener subtítulos

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

Cancelar la suscripción a los agentes de escucha

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

Compatibilidad con idiomas hablados

Obtener una lista de idiomas hablados admitidos

Obtenga una lista de los idiomas hablados admitidos entre los que los usuarios pueden seleccionar al habilitar subtítulos. La propiedad devuelve una matriz de idiomas en formato bcp 47.

const spokenLanguages = teamsCaptions.supportedSpokenLanguages; 

Establecer el Idioma hablado

Pase un valor desde la matriz de idiomas hablados admitidos para asegurarse de que se admite el idioma solicitado. De forma predeterminada, si contoso no proporciona ningún idioma o un idioma no admitido, el idioma hablado tiene como valor predeterminado "en-us".

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

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

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

Compatibilidad con idiomas de subtítulos

Obtener una lista de idiomas de subtítulo admitidos

Si su organización tiene una licencia Premium de Teams activa, puede permitir que los usuarios usen subtítulos traducidos proporcionados por los subtítulos de Teams. En cuanto a los usuarios con una identidad de Microsoft 365, si el organizador de la reunión no tiene una licencia Premium de Teams activa, la comprobación del idioma de subtítulos se realiza en la cuenta de usuarios de Microsoft 365.

La propiedad devuelve una matriz de códigos de idioma de dos letras en ISO 639-1 estándar.

const captionLanguages = teamsCaptions.supportedCaptionLanguages;

Establecer idioma del subtítulo

// ISO 639-1 formatted language code
const language = 'en'; 

// Altneratively, pass a value from the supported caption languages array
const language = captionLanguages[0];
try {
    teamsCaptions.setCaptionLanguage(language);
} catch (e) {
    /* USER ERROR HANDLING CODE HERE */
}

Requisitos previos

Nota:

Tenga en cuenta que deberá tener una aplicación de llamada de voz con el uso de los SDK de llamada de Azure Communication Services para acceder a la característica de subtítulos que se describe en esta guía.

Modelos

Nombre Descripción
CaptionsCallFeature API para la característica de llamada de subtítulos
TeamsCaptions API para subtítulos de Teams
StartCaptionOptions Opciones de subtítulos como idioma hablado
TeamsCaptionsListener Agente de escucha para TeamsCaptions addOnCaptionsReceivedListener
TeamsCaptionsReceivedEvent Objeto de datos recibido para cada evento TeamsCaptionsListener

Obtener característica de subtítulos

Usuarios de identidad externa y usuarios de Microsoft 365

Si va a crear una aplicación que permita a los usuarios unirse a una reunión de Teams

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

Suscribirse a agentes de escucha

Agregar un agente de escucha para recibir el estado habilitado o deshabilitado de los subtítulos

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

Agregar agente de escucha para los datos de subtítulos recibidos

TeamsCaptionsListener captionsListener = (TeamsCaptionsReceivedEvent args) -> {
  // Information about the speaker.
  // CallerInfo participantInfo = args.getSpeaker();
  // The original text with no transcribed.
  // args.getSpokenText();
  // language identifier for the captions text.
  // args.getCaptionLanguage();
  // language identifier for the speaker.
  // args.getSpokenLanguage();
  // The transcribed text.
  // args.getCaptionText();
  // 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() {
  teamsCaptions.addOnCaptionsReceivedListener(captionsListener); 
}

Agregar un agente de escucha para recibir el estado de cambio de idioma hablado activo

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

Agregar un agente de escucha para recibir el estado del idioma del título activo cambiado

public void addOnActiveCaptionLanguageChangedListener() {
    teamsCaptions.addOnActiveCaptionLanguageChangedListener( (PropertyChangedEvent args) -> {
       // teamsCaptions.getActiveCaptionLanguage()
    });
}

Inicio de subtítulos

Una vez configurados todos los agentes de escucha, ahora puede empezar a agregar subtítulos.

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

Detener subtítulos

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

Quitar el agente de escucha recibido de subtítulos

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

Compatibilidad con idiomas hablados

Obtener lista de idiomas hablados admitidos

Obtenga una lista de los idiomas hablados admitidos entre los que los usuarios pueden seleccionar al habilitar subtítulos.

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

Establecer el Idioma hablado

Cuando el usuario selecciona el idioma hablado, la aplicación puede establecer el idioma hablado en el que espera que se generen subtítulos.

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

Compatibilidad con idiomas de subtítulos

Obtener el idioma del subtítulo admitido

Si su organización tiene una licencia Premium de Teams activa, los usuarios de Azure Communication Services pueden habilitar subtítulos traducidos siempre que el organizador de la reunión tenga una licencia Teams Premium. En cuanto a los usuarios con identidades de Microsoft 365, esta comprobación se realiza en su propia cuenta de usuario si el organizador de reuniones no tiene una licencia Teams Premium.

// ISO 639-1 formatted language code
teamsCaptions.getSupportedCaptionLanguages();

Establecer idioma del subtítulo

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

Requisitos previos

Nota:

Tenga en cuenta que deberá tener una aplicación de llamada de voz con el uso de los SDK de llamada de Azure Communication Services para acceder a la característica de subtítulos que se describe en esta guía.

Modelos

Nombre Descripción
CaptionsCallFeature API para la característica de llamada de subtítulos
TeamsCaptions API para subtítulos de Teams
StartCaptionOptions Opciones de subtítulos como idioma hablado
TeamsCaptionsDelegate Delegado para subtítulos de Teams
TeamsCaptionsReceivedEventArgs Objeto de datos recibido para cada evento recibido de subtítulos de Teams

Obtener característica de subtítulos

Usuarios de identidad externa y usuarios de Microsoft 365

Si va a crear una aplicación que permita a los usuarios de Azure Communication Services unirse a una reunión de Teams

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.teamsCaptions) {
                // teams captions
                @State var teamsCaptions = value as? TeamsCaptions
            }
        }
    }
}

Suscribirse a agentes de escucha

Agregar un agente de escucha para recibir subtítulos habilitados o deshabilitados, idioma hablado, estado del idioma del título cambiado y datos recibidos

extension CallObserver: TeamsCaptionsDelegate {
    // listener for receive captions enabled/disabled status
    public func teamsCaptions(_ teamsCaptions: TeamsCaptions, didChangeCaptionsEnabledState args: PropertyChangedEventArgs) {
        // teamsCaptions.isEnabled
    }
    
    // listener for active spoken language state change
    public func teamsCaptions(_ teamsCaptions: TeamsCaptions, didChangeActiveSpokenLanguageState args: PropertyChangedEventArgs) {
        // teamsCaptions.activeSpokenLanguage
    }
    
    // listener for active caption language state change
    public func teamsCaptions(_ teamsCaptions: TeamsCaptions, didChangeActiveCaptionLanguageState args: PropertyChangedEventArgs) {
        // teamsCaptions.activeCaptionLanguage
    }
    
    // listener for captions data received
    public func teamsCaptions(_ teamsCaptions: TeamsCaptions, didReceiveCaptions:TeamsCaptionsReceivedEventArgs) {
            // Information about the speaker.
            // didReceiveCaptions.speaker
            // The original text with no transcribed.
            // didReceiveCaptions.spokenText
            // language identifier for the captions text.
            // didReceiveCaptions.captionLanguage
            // language identifier for the speaker.
            // didReceiveCaptions.spokenLanguage
            // The transcribed text.
            // didReceiveCaptions.captionText
            // 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
    }
}

teamsCaptions.delegate = self.callObserver

Inicio de subtítulos

Una vez configurados todos los agentes de escucha, ahora puede empezar a agregar subtítulos.

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

Detener subtítulos

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

Quitar el agente de escucha recibido de subtítulos

teamsCaptions?.delegate = nil

Compatibilidad con idiomas hablados

Obtener lista de idiomas hablados admitidos

Obtenga una lista de los idiomas hablados admitidos entre los que los usuarios pueden seleccionar al habilitar subtítulos.

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

Establecer el Idioma hablado

Cuando el usuario selecciona el idioma hablado, la aplicación puede establecer el idioma hablado en el que espera que se generen subtítulos.

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

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

Compatibilidad con idiomas de subtítulos

Obtener el idioma del subtítulo admitido

Si su organización tiene una licencia Premium de Teams activa, los usuarios de Azure Communication Services pueden habilitar subtítulos traducidos siempre que el organizador de la reunión tenga una licencia Teams Premium. En cuanto a los usuarios con identidades de Microsoft 365, esta comprobación se realiza en su propia cuenta de usuario si el organizador de reuniones no tiene una licencia Teams Premium.

// ISO 639-1 formatted language code
let captionLanguage : String = "en"
for language in teamsCaptions?.supportedCaptionLanguages ?? [] {
    // choose required language
    captionLanguage = language
}

Establecer idioma del subtítulo

func setCaptionLanguage() {
    guard let teamsCaptions = self.teamsCaptions else {
        return
    }

    teamsCaptions.set(captionLanguage: captionLanguage, completionHandler: { (error) in
        if let error = error {
        }
    })
}

Limpieza de recursos

Si quiere limpiar y quitar una suscripción a Communication Services, puede eliminar el recurso o grupo de recursos. Al eliminar el grupo de recursos, también se elimina cualquier otro recurso que esté asociado a él. Obtenga más información sobre la limpieza de recursos en este documento.

Pasos siguientes

Para más información, consulte los siguientes artículos.