Search code examples
c++text-to-speechsapi

SAPI (Microsoft Speech API) CoCreateInstance failed


I'm trying to run a SAPI sample from a Microsoft sample page.

When I run the application (with VS2010), this line fails:

hr = cpVoice.CoCreateInstance( CLSID_SpVoice );

hr return an error code and all other code is not executed.

I don't know why I'm wrong,, because I think to use correctly the sample code in that page and I've never use this API before.

This is my complete main.cpp file. What I'm missing?

#include "stdafx.h"
#include <sapi.h>
#include <sphelper.h>
#include <atlcomcli.h>

int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hr = S_OK;
    CComPtr <ISpVoice>      cpVoice;
    CComPtr <ISpStream>     cpStream;
    CSpStreamFormat         cAudioFmt;

    //Create a SAPI Voice
    hr = cpVoice.CoCreateInstance( CLSID_SpVoice );

    //Set the audio format
    if(SUCCEEDED(hr))
    {
        hr = cAudioFmt.AssignFormat(SPSF_22kHz16BitMono);
    }

    //Call SPBindToFile, a SAPI helper method,  to bind the audio stream to the file
    if(SUCCEEDED(hr))
    {

        hr = SPBindToFile( L"c:\\ttstemp.wav",  SPFM_CREATE_ALWAYS,
            &cpStream, & cAudioFmt.FormatId(),cAudioFmt.WaveFormatExPtr() );
    }

    //set the output to cpStream so that the output audio data will be stored in cpStream
    if(SUCCEEDED(hr))
    {
        hr = cpVoice->SetOutput( cpStream, TRUE );
    }

    //Speak the text "hello world" synchronously
    if(SUCCEEDED(hr))
    {
        hr = cpVoice->Speak( L"Hello World",  SPF_DEFAULT, NULL );
    }

    //close the stream
    if(SUCCEEDED(hr))
    {
        hr = cpStream->Close();
    }

    //Release the stream and voice object    
    cpStream.Release ();
    cpVoice.Release();

    return 0;
}

Solution

  • You have to initialize the thread using CoInitialize[Ex] prior to using CoCreateInstance API. The error code you are getting should explicitly suggest that: CO_E_NOTINITIALIZED (you should have posted it on your question!).