SAPI实现TTS

废话不多说,直接上代码

//tts_module.h
#ifndef  __TTS_MODULE_HH__
#define  __TTS_MODULE_HH__

#ifdef  WIN32
#ifdef  TTS_MODULE_EXPORTS
#define TTS_MODULE_API __declspec(dllexport)
#else
#define TTS_MODULE_API __declspec(dllimport)
#endif
#else
#define TTS_MODULE_API
#endif

class TTS_MODULE_API TssModule
{
public:
    TssModule();
    ~TssModule();
    int  Initialise();
    int  Readout(const char * text);
    void Uninitialise();

private:
    void* pSpVoice;
};

#endif
//tts_module.cpp
#include "tts_module.h"
#include 

TssModule::TssModule()
{
    pSpVoice = NULL;
}

TssModule::~TssModule()
{

}

int  TssModule::Initialise()
{
    pSpVoice = NULL;
    // Initialize COM
    CoInitialize(NULL);

    // Create the voice interface object
    if (FAILED(CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_INPROC_SERVER, IID_ISpVoice, (void **)&pSpVoice)))
    {
        printf("Fail to create instance of ISpVoice!");
        return -1;
    }

    CComPtr cpEnum;
    CComPtr cpToken;

    //if (FAILED(SpEnumTokens(SPCAT_VOICES, L"Name=Ekho Mandarin", NULL, &cpEnum)))
    if (FAILED(SpEnumTokens(SPCAT_VOICES, L"Name=Microsoft Lili", NULL, &cpEnum)))
    {
        printf("Fail to get voices!");
        return -2;
    }

    //Get the closest token
    if (FAILED(cpEnum->Next(1, &cpToken, NULL)))
    {
        printf("Fail to get voice EkhoVoice!");
        return -3;
    }

    //set the voice 
    if (FAILED(((ISpVoice*)pSpVoice)->SetVoice(cpToken)))
    {
        printf("Fail to set voice EkhoVoice!");
        return -4;
    }

    return 0;
}

int TssModule::Readout(const char * text)
{
    int nLen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, text, -1, NULL, 0);
    if (nLen == 0)
    {
        printf("MultiByteToWideChar get length = 0");
        return -1;
    }
    wchar_t* pResult = new wchar_t[nLen];
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, text, -1, pResult, nLen);

    ((ISpVoice*)pSpVoice)->Speak(pResult, SPF_DEFAULT, NULL);
    delete pResult;
    return 0;
}

void TssModule::Uninitialise()
{
    CoUninitialize();
}

你可能感兴趣的:(c++)