linux版本中间件

TtsBaidu.cpp 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "TtsBaidu.h"
  2. #include"Md5.h"
  3. #include"ttsapi/speech.h"
  4. //#include <unistd.h>
  5. #include <boost/filesystem.hpp>
  6. namespace fs = boost::filesystem;
  7. TtsBaidu::TtsBaidu()
  8. {
  9. }
  10. TtsBaidu::~TtsBaidu()
  11. {
  12. }
  13. void TtsBaidu::Init(std::string ttsPath)
  14. {
  15. m_ttsPath = ttsPath;
  16. m_ttsPath = m_ttsPath + "/";
  17. boost::filesystem::path fp(m_ttsPath);
  18. if (!boost::filesystem::exists(fp)) // 判断路径是否存在,不存在则创建路径
  19. {
  20. if (!boost::filesystem::create_directories(fp))
  21. {
  22. std::cout << "TTS目录创建失败" << std::endl;
  23. }
  24. }
  25. }
  26. bool TtsBaidu::TextToAudio(std::string Content, std::string& FileName)
  27. {
  28. aip::Speech g_client(app_id, api_key, secret_key);
  29. std::ofstream ofile;
  30. std::string file_ret;
  31. md5space::MD5 md(Content);
  32. std::string ContentMd5 = md.getMd5();
  33. ContentMd5.append(".mp3");
  34. /*ContentMd5.append(".wav");*/
  35. std::string AudioName = ContentMd5;
  36. std::string resultName = m_ttsPath + AudioName;
  37. //if ((access(resultName.c_str(), 0)) != -1) //若文件已存在不再转换
  38. //{
  39. // FileName = resultName;
  40. // return true;
  41. //}
  42. fs::path filePath = (resultName);
  43. if (fs::exists(filePath))
  44. {
  45. FileName = resultName;
  46. return true;
  47. }
  48. ofile.open(resultName, std::ios::out | std::ios::binary);
  49. Json::Value result = g_client.text2audio(Content, aip::null, file_ret);
  50. // 如果error_code字段为空则说明合成成功,返回mp3文件内容,否则json数据为相应的错误反回结果
  51. if (result["error_code"] == Json::nullValue)
  52. {
  53. ofile << file_ret;
  54. FileName = resultName;
  55. return true;
  56. }
  57. return false;
  58. }