2013-03-22 11 views
1

我正在開發一個使用Microsoft SAPI5語音引擎的應用程序。但是,我已經撞牆了。我一直試圖使用存儲來自用戶輸入的變量的數據,所以TTS引擎可以重複它。但是sapi5語音函數不允許字符串,字符串或其他類型,除了LPCWSTR,我的研究是一個指向寬字符串的指針,所以它不應該接受wstrings?存儲一個變量,用於保存sapi5中的用戶輸入數據speak function

下面是一些示例代碼從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

回答

0

後約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重複(所以轉換後的字符串可以在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); 
} 

我希望我的回答能幫助那些和我有同樣問題的人。

我會更詳細地解釋我的答案,但我需要一些睡眠,所以請接受我誠摯的道歉:-)。

相關問題