TTS in C++ Got an error when I was trying to use a string variable

43 Views Asked by At

I created a void named "bot" to get text and speak it using a variable named "text". Like this, void bot(string text). To use this void bot("Hello") or bot("Hi, my name is blah blah") but it is not working.

Here is my code,

#include <iostream>
#include <sapi.h>
#include <string>

using namespace std;

void bot(string text)
{
    ISpVoice* pVoice = NULL;
    if (FAILED(::CoInitialize(NULL)))
    {
        exit(1);
    }
    HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void**)&pVoice);
    if (SUCCEEDED(hr))
    {
        hr = pVoice->Speak(text, 0, NULL);
        pVoice->Release();
        pVoice = NULL;
    }
    ::CoUninitialize();
}

int main()
{
    bot("Hello");
    return 0;
}

Any help please....

I tried like this,


    {
        hr = pVoice->Speak(L + text, 0, NULL);
        pVoice->Release();
        pVoice = NULL;
    }

And this,

    string sentence = text;
    {
        hr = pVoice->Speak(sentence, 0, NULL);
        pVoice->Release();
        pVoice = NULL;
    }

But it didn't work.

1

There are 1 best solutions below

0
john On

Like this

int main()
{
    bot(L"Hello"); // L for wide string
    return 0;
}

and this

void bot(wstring text) // wide string
{
    ...
}

and this

hr = pVoice->Speak(text.c_str(), 0, NULL); // c_str() for C string

Speak apparently requires a wide C string. wstring is the type for a wide C++ string. c_str() is the way you 'translate' from C++ strings to C strings. L"hello" is the way you write a wide string literal.