gpt4 book ai didi

c++ - 在 sapi5 speak 函数中存储一个保存用户输入数据的变量

转载 作者:太空宇宙 更新时间:2023-11-04 14:09:11 24 4
gpt4 key购买 nike

我正在开发一个使用 Microsoft SAPI5 语音引擎的应用程序。但是,我碰壁了。我一直在尝试使用存储用户输入的变量中的数据,以便 TTS 引擎可以重复它。但是 sapi5 语音函数不允许字符串、wstrings 或其他类型,除了 LPCWSTR,根据我的研究,它是一个指向宽字符串的指针,所以它不应该接受 wstrings 吗?

这是来自 msdn 的一些示例代码:

#include <stdafx.h>
#include <sapi.h>

int main(int argc, char* argv[])
{
ISpVoice * pVoice = NULL;

if (FAILED(::CoInitialize(NULL)))
return FALSE;

HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice;);
if( SUCCEEDED( hr ) )
{
hr = pVoice->Speak(L"Hello world", 0, NULL);
pVoice->Release();
pVoice = NULL;
}

::CoUninitialize();
return TRUE;
}

比方说我有这段代码:

...
wstring text;
if( SUCCEEDED( hr ) )
{
wcin >> text;
hr = pVoice->Speak(text, SPF_IS_XML, NULL);
pVoice->Release();
pVoice = NULL;
}
...

但这行不通。我将如何存储允许 LPCWSTR 类型的变量?我是 C++ 的新手,这是我第一次遇到这类问题,所以这对我来说很陌生。

我看到关于这个主题的 OP 有完全相同的问题:https://stackoverflow.com/questions/12292790/how-do-i-use-variables-in-sapi-tts

最佳答案

经过大约 2 小时的扎实研究,我在 msdn 上找到了一篇关于将字符串转换为 LPCWSTR 格式的文章。代码如下:

std::wstring s2ws(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}

然后我将这段代码包含到我的项目中,然后为TTS引擎初始化函数创建了一个名为LPCWSTR Repeat的函数参数(这样转换后的字符串就可以在TTS函数中使用,引擎会说出转换后的字符串 ) .

static int TTS_Speak_Dialogue(LPCWSTR Repeat)
{
// Set Sapi5 voice properties
ISpVoice * pVoice = NULL;

if (FAILED(::CoInitialize(NULL)))
return FALSE;

// Create new instance of Sapi5 once initialized in COM
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);

if( SUCCEEDED( hr ) )
{
hr = pVoice->Speak(Repeat, SPF_IS_XML, NULL);
pVoice->Release();
pVoice = NULL;
}

::CoUninitialize();
return TRUE;
}

然后我创建了另一个函数来管理转换和管理用户输入,以便 TTS 引擎可以重复它。

static void convert_string() 
{
// Declare a string type variable
string UserInput;
// Now get input from user
cout << "Get the TTS to repeat Input : ";
cin >> UserInput;

// Convert string to LPCWSTR!
std::wstring stemp = s2ws(UserInput);
// UserInput string now converted to result
LPCWSTR result = stemp.c_str();

// Call the TTS engine function and use the converted string
TTS_Speak_Dialogue(result);
}

希望我的回答能帮到和我有同样问题的人。

我会更详细地解释我的答案,但我需要一些 sleep ,所以请接受我诚挚的歉意:-)。

关于c++ - 在 sapi5 speak 函数中存储一个保存用户输入数据的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15573246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com