> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# XSpeechSynthesizerCreate

> XSpeechSynthesizerCreate

# XSpeechSynthesizerCreate

Cria um sintetizador de fala.

## Sintaxe

```cpp theme={null}
HRESULT XSpeechSynthesizerCreate(  
         XSpeechSynthesizerHandle* speechSynthesizer  
)  
```

### Parâmetros

*speechSynthesizer*   \_Out\_\
Tipo: XSpeechSynthesizerHandle\*

O identificador do sintetizador de fala criado.

### Valor retornado

Tipo: [HRESULT](https://learn.microsoft.com/openspecs/windows_protocols/ms-erref/0642cb2f-2075-4469-918c-4441e69c548a)

Retorna **S\_OK** se for bem-sucedida; caso contrário, retorna um código de erro. Para obter uma lista de códigos de erro, consulte [Códigos de erro](/pt-BR/reference/errorcodes).

## Comentários

<Note>Não é seguro chamar esta função em um thread sensível ao tempo. Para obter mais informações, consulte [Threads sensíveis ao tempo](https://learn.microsoft.com/gaming/gdk/docs/gdk-dev/console-dev/overviews/threads/time-sensitive-threads).</Note>

Use esta função para criar e receber o identificador de uma nova instância de sintetizador de fala, que fornece acesso à funcionalidade de um mecanismo de síntese de fala instalado, ou *voz*.

Por padrão, uma nova instância de sintetizador de fala usa a voz atual do sistema. Para enumerar e obter informações sobre as vozes instaladas no dispositivo atual, use a função [XSpeechSynthesizerEnumerateInstalledVoices](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizerenumerateinstalledvoices) junto com a função de retorno de chamada [XSpeechSynthesizerInstalledVoicesCallback](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizerinstalledvoicescallback). Para cada voz instalada, a estrutura [XSpeechSynthesizerVoiceInformation](/pt-BR/reference/system/xspeechsynthesizer/structs/xspeechsynthesizervoiceinformation) fornece a ID da voz, a descrição, o texto de exibição, o gênero, o idioma e outras informações. Invoque [XSpeechSynthesizerSetCustomVoice](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizersetcustomvoice) para usar uma voz instalada diferente ou invoque [XSpeechSynthesizerSetDefaultVoice](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizersetdefaultvoice) para usar novamente a voz atual do sistema.

Depois de criar um identificador de sintetizador de fala e especificar uma voz, use a função [XSpeechSynthesizerCreateStreamFromText](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizercreatestreamfromtext) para criar um fluxo do sintetizador de fala e sintetizar fala a partir de texto sem formatação. Use as funções [XSpeechSynthesizerGetStreamDataSize](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizergetstreamdatasize) e [XSpeechSynthesizerGetStreamData](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizergetstreamdata) para obter os dados de áudio da fala sintetizada do fluxo do sintetizador de fala e, em seguida, use a função [XSpeechSynthesizerCloseStreamHandle](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizerclosestreamhandle) para fechar o fluxo do sintetizador de fala depois que todas as operações assíncronas pendentes forem concluídas.

Use a função [XSpeechSynthesizerCloseHandle](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizerclosehandle) para fechar o sintetizador de fala e liberar os recursos do sistema depois de terminar de usar o sintetizador de fala.

Para evitar vazamentos de memória, chame a função [XSpeechSynthesizerCloseHandle](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizerclosehandle) para fechar um identificador de sintetizador de fala depois de concluir todas as operações que estão usando o identificador.

O exemplo a seguir demonstra como sintetizar fala a partir de texto sem formatação usando um sintetizador de fala e uma voz instalada, e como sintetizar dados de áudio com um fluxo do sintetizador de fala. As funções **XSpeechSynthesizerCreate** e **XSpeechSynthesizerSetCustomVoice** criam uma instância de sintetizador de fala e, opcionalmente, atribuem a ela uma voz personalizada se uma ID de voz for especificada em *voiceId*. Em seguida, a função **XSpeechSynthesizerCreateStreamFromText** cria um fluxo do sintetizador de fala e sintetiza a fala a partir do texto sem formatação especificado em *textToSpeak*. Depois que o fluxo é criado, as funções **XSpeechSynthesizerGetStreamDataSize** e **XSpeechSynthesizerGetStreamData** recuperam do fluxo os dados de áudio da fala sintetizada a serem reproduzidos. Por fim, após a conclusão da reprodução dos dados de áudio, as funções **XSpeechSynthesizerCloseStreamHandle** e **XSpeechSynthesizerCloseHandle** fecham o fluxo do sintetizador de fala e o sintetizador de fala.

```cpp theme={null}
HRESULT Game::SynthesizeSpeech(
    const char* textToSpeak,
    const char* voiceId)
{
    // Create a new speech synthesizer.
    XSpeechSynthesizerHandle ssHandle = nullptr;
    if (FAILED(XSpeechSynthesizerCreate(&ssHandle))) { return E_FAIL; }

    // If a voice ID was specified, attempt to set the speech synthesizer to
    // use the specified voice. Note that voiceId has a default value of nullptr, 
    // as specified in its function declaration.
    if (voiceId != nullptr) 
    {
        if (FAILED(XSpeechSynthesizerSetCustomVoice(ssHandle, voiceId))) { return E_FAIL; }
    }

    // Create a new speech synthesizer stream from the specified text.
    XSpeechSynthesizerStreamHandle ssStreamHandle = nullptr;
    if (FAILED(XSpeechSynthesizerCreateStreamFromText(ssHandle, textToSpeak, &ssStreamHandle))) { return E_FAIL; }

    // Get the size of the buffer needed for the audio data from our stream.
    size_t bufferSize;
    if (FAILED(XSpeechSynthesizerGetStreamDataSize(ssStreamHandle, &bufferSize))) { return E_FAIL; }

    // Define the buffer, then retrieve the audio data from our stream.
    std::vector<char> streamData;
    streamData.resize(bufferSize);
    if (FAILED(XSpeechSynthesizerGetStreamData(ssStreamHandle, bufferSize, streamData.data(), &bufferSize))) { return E_FAIL; }

    // We now have audio data from the speech synthesizer stream, so let's play it. 
    // For the purposes of this example, the sound is played synchronously, so that we don't
    // risk having an outstanding asynchronous operation when we close the stream.
    PlaySoundW(reinterpret_cast<LPCWSTR>(streamData.data()), nullptr, SND_MEMORY);

    // We're done with the speech synthesizer stream, so let's close it.
    if (FAILED(XSpeechSynthesizerCloseStreamHandle(ssStreamHandle))) { return E_FAIL; }

    // We're done with the speech synthesizer, so let's close that, too.
    if (FAILED(XSpeechSynthesizerCloseHandle(ssHandle))) { return E_FAIL; }

    return S_OK;
}
```

## Requisitos

**Cabeçalho:** XSpeechSynthesizer.h

**Biblioteca:** xgameruntime.lib

**Plataformas com suporte:** Windows, consoles da família XBOX One e consoles XBOX Series

## Documentação conceitual

* [Conversão de texto em fala](/pt-BR/build/console-features/text-to-speech/text-to-speech)
* [Threads sensíveis ao tempo](https://learn.microsoft.com/gaming/gdk/docs/gdk-dev/console-dev/overviews/threads/time-sensitive-threads)

## Confira também

[XAccessibility](/pt-BR/reference/system/xaccessibility/xaccessibility_members)\
[XSpeechSynthesizerCloseHandle](/pt-BR/reference/system/xspeechsynthesizer/functions/xspeechsynthesizerclosehandle)\
[XSpeechSynthesizer](/pt-BR/reference/system/xspeechsynthesizer/xspeechsynthesizer_members)


## Related topics

- [XSpeechSynthesizerCreate](/reference/system/xspeechsynthesizer/functions/xspeechsynthesizercreate.md)
- [XSpeechSynthesizerCreateStreamFromSsml](/reference/system/xspeechsynthesizer/functions/xspeechsynthesizercreatestreamfromssml.md)
- [XSpeechSynthesizerCreateStreamFromText](/reference/system/xspeechsynthesizer/functions/xspeechsynthesizercreatestreamfromtext.md)
