1.下载SDK包
https://www.microsoft.com/en-us/download/details.aspx?id=10121
2.直接上代码
// SpeechRecognition.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <sapi.h> //导入语音头文件
#include <atlstr.h>
#include <iostream>
#pragma comment(lib,"sapi.lib") //导入语音头文件库
#include <sphelper.h>
#pragma once
const int WM_RECORD = WM_USER + 100;//定义消息
using namespace std;
//文字转语音
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(1); //设置速度,范围是 -10 - 10
hr = pVoice->Speak(speakContent, 0,NULL);
pVoice->Release();
pVoice = NULL;
}
else{
MessageBox(NULL, (LPCWSTR)L"SpVoice接口初始化失败!", (LPCWSTR)L"提示", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2);
}
//释放com资源
::CoUninitialize();
}
int _tmain(int argc, _TCHAR* argv[])
{
/**FILE *p = NULL;
p = fopen("data.txt","r");
if (p == NULL)
{
cout << "not find file! data.txt " << endl;
Sleep(3000);
return 0;
}
string strtemp;
char line[2048];
while (fgets(line, 512, p))
{
if (strlen(line) < 4)
{
continue;
}
//判断当前读取到的字符串是否有换行符
if (line[strlen(line) - 1] == '\n')
{
//有换换行符就去掉换行符00
line[strlen(line) - 1] = 0;
}
strtemp += line;
}
LPCTSTR lpstr = (LPCTSTR)strtemp.c_str();**/
MSSSpeak(LPCTSTR("hello,世界!"));
return 0;
}