Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

93 lines
3.6KB

  1. """
  2. baidu voice service
  3. """
  4. import json
  5. import os
  6. import time
  7. from aip import AipSpeech
  8. from bridge.reply import Reply, ReplyType
  9. from common.log import logger
  10. from common.tmp_dir import TmpDir
  11. from voice.voice import Voice
  12. from voice.audio_convert import get_pcm_from_wav
  13. from config import conf
  14. """
  15. 百度的语音识别API.
  16. dev_pid:
  17. - 1936: 普通话远场
  18. - 1536:普通话(支持简单的英文识别)
  19. - 1537:普通话(纯中文识别)
  20. - 1737:英语
  21. - 1637:粤语
  22. - 1837:四川话
  23. 要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号,
  24. 之后创建一个新应用, 然后在应用管理的"查看key"中获得 API Key 和 Secret Key
  25. 然后在 config.json 中填入这两个值, 以及 app_id, dev_pid
  26. """
  27. class BaiduVoice(Voice):
  28. def __init__(self):
  29. try:
  30. curdir = os.path.dirname(__file__)
  31. config_path = os.path.join(curdir, "config.json")
  32. bconf = None
  33. if not os.path.exists(config_path): #如果没有配置文件,创建本地配置文件
  34. bconf = { "lang": "zh", "ctp": 1, "spd": 5,
  35. "pit": 5, "vol": 5, "per": 0}
  36. with open(config_path, "w") as fw:
  37. json.dump(bconf, fw, indent=4)
  38. else:
  39. with open(config_path, "r") as fr:
  40. bconf = json.load(fr)
  41. self.app_id = conf().get('baidu_app_id')
  42. self.api_key = conf().get('baidu_api_key')
  43. self.secret_key = conf().get('baidu_secret_key')
  44. self.dev_id = conf().get('baidu_dev_pid')
  45. self.lang = bconf["lang"]
  46. self.ctp = bconf["ctp"]
  47. self.spd = bconf["spd"]
  48. self.pit = bconf["pit"]
  49. self.vol = bconf["vol"]
  50. self.per = bconf["per"]
  51. self.client = AipSpeech(self.app_id, self.api_key, self.secret_key)
  52. except Exception as e:
  53. logger.warn("BaiduVoice init failed: %s, ignore " % e)
  54. def voiceToText(self, voice_file):
  55. # 识别本地文件
  56. logger.debug('[Baidu] voice file name={}'.format(voice_file))
  57. pcm = get_pcm_from_wav(voice_file)
  58. res = self.client.asr(pcm, "pcm", 16000, {"dev_pid": self.dev_id})
  59. if res["err_no"] == 0:
  60. logger.info("百度语音识别到了:{}".format(res["result"]))
  61. text = "".join(res["result"])
  62. reply = Reply(ReplyType.TEXT, text)
  63. else:
  64. logger.info("百度语音识别出错了: {}".format(res["err_msg"]))
  65. if res["err_msg"] == "request pv too much":
  66. logger.info(" 出现这个原因很可能是你的百度语音服务调用量超出限制,或未开通付费")
  67. reply = Reply(ReplyType.ERROR,
  68. "百度语音识别出错了;{0}".format(res["err_msg"]))
  69. return reply
  70. def textToVoice(self, text):
  71. result = self.client.synthesis(text, self.lang, self.ctp, {
  72. 'spd': self.spd, 'pit': self.pit, 'vol': self.vol, 'per': self.per})
  73. if not isinstance(result, dict):
  74. fileName = TmpDir().path() + 'reply-' + str(int(time.time())) + '.mp3'
  75. with open(fileName, 'wb') as f:
  76. f.write(result)
  77. logger.info(
  78. '[Baidu] textToVoice text={} voice file name={}'.format(text, fileName))
  79. reply = Reply(ReplyType.VOICE, fileName)
  80. else:
  81. logger.error('[Baidu] textToVoice error={}'.format(result))
  82. reply = Reply(ReplyType.ERROR, "抱歉,语音合成失败")
  83. return reply