让萨皮说一串

Getting Sapi to say a string

本文关键字:一串      更新时间:2023-10-16

我有一个程序,要求人们将他们想要的文本翻译成Al Bhed,这只是一个密码,字母在其中移动,并由SAPI说出。字符串翻译得很好,但这段代码:

hr = pVoice->Speak(sTranslated, 0, NULL);

将不起作用,因为它说"不存在从‘std::string’到‘const WCHAR*’的合适的转换函数。我只想让声音说出翻译后的字符串。我该怎么做?

首先需要将使用类型charstd::string内容转换为使用类型wchar_tstd::wstring。这是因为ISpVoice::Speak()函数要求第一个参数的类型为LPCWSTR,IOW是"指向宽字符串的常量指针"。以下功能可能对您有所帮助。

inline std::wstring s2w(const std::string &s, const std::locale &loc = std::locale())
{
    typedef std::ctype<wchar_t> wchar_facet;
    std::wstring return_value;
    if (s.empty())
    {
        return return_value;
    }
    if (std::has_facet<wchar_facet>(loc))
    {
        std::vector<wchar_t> to(s.size() + 2, 0);
        std::vector<wchar_t>::pointer toPtr = &to[0];
        const wchar_facet &facet = std::use_facet<wchar_facet>(loc);
        if (0 != facet.widen(s.c_str(), s.c_str() + s.size(), toPtr))
        {
            return_value = to.data();
        }
    }
    return return_value;
}

然后将代码行更改为以下内容。

hr = pVoice->Speak(s2w(sTranslated).c_str(), 0, NULL);

c_str()方法返回一个指向std::wstring对象的"等价C字符串"的指针。IOW,它返回一个指向以null结尾的宽字符串的指针。