当前位置:   article > 正文

C++ 简单的语音合成(TTS,即文字转语音)类_c++ tts

c++ tts

如果出现以下错误:

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

关闭SDL:

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

转载于

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

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

  1. #pragma once
  2. #include <Windows.h>
  3. #include "sapi.h"
  4. #include <list>
  5. #include <string>
  6. #include "sphelper.h"
  7. #pragma comment(lib, "sapi.lib")
  8. class TTS
  9. {
  10. public:
  11. TTS();
  12. ~TTS();
  13. bool Speak(std::wstring);
  14. bool IsUseful();
  15. private:
  16. ISpVoice* m_pSpVoice;
  17. bool InitVoice();
  18. void StopVoice();
  19. };

tts.cpp

  1. #include "tts.h"
  2. TTS::TTS()
  3. {
  4. m_pSpVoice = nullptr;
  5. }
  6. TTS::~TTS()
  7. {
  8. StopVoice();
  9. ::CoUninitialize();
  10. }
  11. bool TTS::InitVoice()
  12. {
  13. HRESULT ret = ::CoInitialize(NULL);
  14. ret = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_INPROC_SERVER, IID_ISpVoice, (void**)&m_pSpVoice);
  15. if (0 == ret && m_pSpVoice)
  16. {
  17. m_pSpVoice->SetVolume(80);
  18. IEnumSpObjectTokens *pSpEnumTokens = NULL;
  19. if (SUCCEEDED(SpEnumTokens(SPCAT_VOICES, NULL, NULL, &pSpEnumTokens))) //找到lili语音进行朗读, 否则就跳出
  20. {
  21. ISpObjectToken *pSpToken = NULL;
  22. while (SUCCEEDED(pSpEnumTokens->Next(1, &pSpToken, NULL)) && pSpToken != NULL)
  23. {
  24. LPWSTR pId = new WCHAR[32];
  25. pSpToken->GetId(&pId);
  26. int nLen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)pId, -1, NULL, 0, NULL, NULL);
  27. char *s = new char[nLen + 1];
  28. WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)pId, -1, s, nLen, NULL, NULL);
  29. if (0 == strcmp(s, ("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\MS-Lili-2052-20-DSK")))
  30. {
  31. m_pSpVoice->SetVoice(pSpToken); // 设置lili语音
  32. pSpToken->Release();
  33. delete[] s;
  34. break;
  35. }
  36. delete[] s;
  37. pSpToken->Release();
  38. }
  39. pSpEnumTokens->Release();
  40. }
  41. return true;
  42. }
  43. else
  44. {
  45. }
  46. return false;
  47. }
  48. bool TTS::Speak(std::wstring word)
  49. {
  50. StopVoice();
  51. if (InitVoice())
  52. {
  53. HRESULT ret = m_pSpVoice->Speak(word.c_str(), SPF_ASYNC, NULL);
  54. return ret;
  55. }
  56. else
  57. {
  58. return false;
  59. }
  60. }
  61. bool TTS::IsUseful()
  62. {
  63. bool bRet = InitVoice();
  64. StopVoice();
  65. return bRet;
  66. }
  67. void TTS::StopVoice()
  68. {
  69. if (m_pSpVoice!=nullptr)
  70. {
  71. m_pSpVoice->Release();
  72. }
  73. }

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

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/949934
推荐阅读
相关标签
  

闽ICP备14008679号