vlambda博客
学习文章列表

C语言实现将文字转为语音


C语言将文字实现成语音

直接上代码吧,具体要改成啥样看你咯!

#include<iostream>

using namespace std;

#include <sapi.h> //导入语音头文件

#include <string>

#pragma comment(lib,"sapi.lib") //导入语音头文件库



void  MSSSpeak(LPCTSTR speakContent)// speakContent为LPCTSTR型的字符串,调用此函数即可将文字转为语音

{

ISpVoice *pVoice = NULL;



//初始化COM接口



if (FAILED(::CoInitialize(NULL)))

MessageBox(NULL, (LPCWSTR)L"COM接口初始化失败!", (LPCWSTR)L"提示", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2);



//获取SpVoice接口



HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void**)&pVoice);





if (SUCCEEDED(hr))

{

pVoice->SetVolume((USHORT)100); //设置音量,范围是 0 -100

pVoice->SetRate(0); //设置速度,范围是 -10 - 10

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



pVoice->Release();



pVoice = NULL;

}



//释放com资源

::CoUninitialize();

}

//string转换车wstring  

std::wstring  StringToWString(const std::string& s)

{

std::wstring wszStr;



int nLength = MultiByteToWideChar(CP_ACP, 0, s.c_str(), -1, NULL, NULL);

wszStr.resize(nLength);

LPWSTR lpwszStr = new wchar_t[nLength];

MultiByteToWideChar(CP_ACP, 0, s.c_str(), -1, lpwszStr, nLength);

wszStr = lpwszStr;

delete[] lpwszStr;

return wszStr;

}

void read(string temp) {


wstring a = StringToWString(temp);

LPCWSTR str = a.c_str();

/*不知道为什么Cstr不行*/

MSSSpeak(str);

cout << "朗读结束\n";

}



int  main()

{

char  buf[128];

int i;

while (1)

{

cout << "输入1继续程序,输入2退出\n";

cin >> i;

switch (i)

{

case 1: cout << "输入一句话\n";

cin >> buf;

read(buf);

break;

case 2:break;


}

if (i == 2)

break;

}

return 0;

}


扫描二维码

这世上,没有谁活得比谁容易,只是有人在呼天抢地,有人在默默努力。I