Reputation: 1372
I'd like to add text to speech to my app and this API looks nice and simple:
SpVoice spVoice = new SpVoice();
spVoice.Speak("Hello World", SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
the problem is i can't figure out how to compiler this. Is there a package i have to download first? is there a header and a .lib or .dll i can link with?
i have a basic, vanilla c++ MFC application (no 'using' or 'import' whatever they are, just old fashioned #include). i hope someone can help, thanks.
Upvotes: 0
Views: 1617
Reputation: 3102
As Hans Passant pointed out, you do need to initialize COM using either CoInitialize (http://msdn.microsoft.com/en-us/library/windows/desktop/ms678543%28v=vs.85%29.aspx) or CoInitializeEx (http://msdn.microsoft.com/en-us/library/windows/desktop/ms695279%28v=vs.85%29.aspx) and then unitialize COM using CoUninitialize (http://msdn.microsoft.com/en-us/library/windows/desktop/ms688715%28v=vs.85%29.aspx) in order to get this to work.
The following is a complete sample.
// Including sdkddkver.h defines the highest available Windows platform.
#include <sdkddkver.h>
#include <stdio.h>
#include <tchar.h>
#include <atlbase.h>
#include <Windows.h>
#include <sapi.h>
#include <string>
int wmain(int argc, wchar_t* argv[])
{
HRESULT hr = ::CoInitialize(nullptr);
if (FAILED(hr))
{
return EXIT_FAILURE;
}
std::wstring text;
if (1 == argc)
{
text = L"Hello World! It truly is a wonderful day to be alive.";
}
else
{
for (int i = 1; i < argc; ++i)
{
text += argv[i];
if (i + 1 < argc)
{
text += L" ";
}
}
}
CComPtr<ISpVoice> cpVoice;
// Create a SAPI voice
hr = cpVoice.CoCreateInstance(CLSID_SpVoice);
// set the output to the default audio device
if (SUCCEEDED(hr))
{
hr = cpVoice->SetOutput(NULL, TRUE);
}
// Speak the text
if (SUCCEEDED(hr))
{
hr = cpVoice->Speak(text.c_str(), SPF_PURGEBEFORESPEAK, NULL);
}
::CoUninitialize();
if (SUCCEEDED(hr))
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Upvotes: 1
Reputation: 3102
That looks like C# to me and not C++. In order to do it in C++ you need to include sapi.h and link with sapi.lib. Then you can do the following.
HRESULT hr = S_OK;
CComPtr<ISpVoice> cpVoice;
// Create a SAPI voice
hr = cpVoice.CoCreateInstance(CLSID_SpVoice);
// set the output to the default audio device
if (SUCCEEDED(hr))
{
hr = cpVoice->SetOutput( NULL, TRUE );
}
// Speak the text
if (SUCCEEDED(hr))
{
hr = cpVoice->Speak(L"Hello World", SPF_PURGEBEFORESPEAK, NULL);
}
See the following resource for more information.
Simple TTS Guide SAPI 5.4: http://msdn.microsoft.com/en-us/library/ee431810%28v=vs.85%29.aspx
Upvotes: 2