c++语音播报

如果出现以下错误:

error C4996: ‘GetVersionExA': 被声明为已否决

关闭SDL:

Project Properties > Configuration Properties > C/C++ > General > SDL checks关掉

转载于

C++ 简单的语音合成(TTS,即文字转语音)类_少年磊的博客-CSDN博客_c++ tts

微软win7及以上版本自带的语音合成引擎,可以直接拿来用,不需要额外的dll文件,只需要引用头文件即可, 封装一个简单的类用来做语音合成如下:
tts.h

#pragma once
#include 
#include "sapi.h"
#include 
#include 
#include "sphelper.h"
#pragma comment(lib, "sapi.lib")
 
 
class TTS
{
public:
	TTS();
	~TTS();
	bool Speak(std::wstring);
	bool IsUseful();
 
private:
	ISpVoice*	m_pSpVoice;
 
	bool InitVoice();
	void StopVoice();
};
 

tts.cpp

#include "tts.h"
 
 
TTS::TTS()
{
	m_pSpVoice = nullptr;
}
 
 
TTS::~TTS()
{
	StopVoice();
	::CoUninitialize();
}
 
bool TTS::InitVoice()
{
	HRESULT ret = ::CoInitialize(NULL);
	ret = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_INPROC_SERVER, IID_ISpVoice, (void**)&m_pSpVoice);
	if (0 == ret && m_pSpVoice)
	{
		m_pSpVoice->SetVolume(80);
 
		IEnumSpObjectTokens *pSpEnumTokens = NULL;
		if (SUCCEEDED(SpEnumTokens(SPCAT_VOICES, NULL, NULL, &pSpEnumTokens)))		//找到lili语音进行朗读, 否则就跳出
		{
			ISpObjectToken *pSpToken = NULL;
			while (SUCCEEDED(pSpEnumTokens->Next(1, &pSpToken, NULL)) && pSpToken != NULL)
			{
				LPWSTR pId = new WCHAR[32];
				pSpToken->GetId(&pId);
 
				int nLen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)pId, -1, NULL, 0, NULL, NULL);
 
				char *s = new char[nLen + 1];
				WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)pId, -1, s, nLen, NULL, NULL);
 
				if (0 == strcmp(s, ("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\MS-Lili-2052-20-DSK")))
				{
					m_pSpVoice->SetVoice(pSpToken);      // 设置lili语音
					pSpToken->Release();
					delete[] s;
					break;
				}
				delete[] s;
				pSpToken->Release();
			}
			pSpEnumTokens->Release();
		}
		return true;
	}
	else
	{
		
	}
	return false;
}
 
bool TTS::Speak(std::wstring word)
{
	StopVoice();
	if (InitVoice())
	{
		HRESULT ret = m_pSpVoice->Speak(word.c_str(), SPF_ASYNC, NULL);
		return ret;
	}
	else
	{
		return false;
	}
 
}
 
bool TTS::IsUseful()
{
	bool bRet = InitVoice();
	StopVoice();
	return bRet;
}
 
void TTS::StopVoice()
{
	if (m_pSpVoice!=nullptr)
	{
		m_pSpVoice->Release();
	}
}

实例化对象,使用Speak函数就行了,后一次会把前一次没播放完的停掉,注意参数是wstring型 

下面链接是Qt实现的语音播报功能,可以调节音量、音色、播报速率,跨平台,功能更强大:

Qt的QTextToSpeech类实现语音播报功能

你可能感兴趣的:(c++,开发语言)