在c++窗口中使用SpVoice
Using SpVoice in c++ windows
我想在我的应用程序中添加文本到语音,这个API看起来很好,很简单:
SpVoice spVoice = new SpVoice();
spVoice.Speak("Hello World", SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
问题是我不知道如何编译这个。我是否需要先下载一个软件包?是否有一个头和。lib或。dll我可以链接?
我有一个基本的,香草的c++ MFC应用程序(没有'使用'或'导入'无论他们是什么,只是老式的#include)。我希望有人能帮忙,谢谢。
这看起来像c#而不是c++。为了在c++中做到这一点,您需要包含sapi.h并链接到sapi.lib。然后您可以执行以下操作。
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);
}
更多信息请参见下面的参考资料。
Simple TTS Guide SAPI 5.4: http://msdn.microsoft.com/en-us/library/ee431810%28v=vs.85%29.aspx
正如Hans Passant指出的那样,您确实需要使用CoInitialize (http://msdn.microsoft.com/en-us/library/windows/desktop/ms678543%28v=vs.85%29.aspx)或CoInitializeEx (http://msdn.microsoft.com/en-us/library/windows/desktop/ms695279%28v=vs.85%29.aspx)初始化COM,然后使用CoUninitialize (http://msdn.microsoft.com/en-us/library/windows/desktop/ms688715%28v=vs.85%29.aspx)初始化COM,以便使其工作。
以下是一个完整的示例。
// 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;
}
相关文章: