# -*- coding: utf-8 -*- from __future__ import division from .__load__ import * # 口 说话 class Mouth(object): tool = {} def init(self, robot): self.robot = robot # 播放器 self.speaker = None # 对话 self.onSay = None return self def say(self, msg, cache=False, plugin='', completed=None): if self.onSay: self.robot.logger.info(self.log('onSay: {}'.format(msg))) if plugin != '': self.onSay("[{}] {}".format(plugin, msg)) else: self.onSay(msg) self.onSay = None if plugin != '': self.robot.brain.addMemory(1, "[{}] {}".format(plugin, msg)) else: self.robot.brain.addMemory(1, msg) pattern = r'^https?://.+' if re.match(pattern, msg): self.robot.logger.info(self.log('内容包含URL,无法读取')) return voice = '' self.robot.logger.info(self.log('获取文字 - ' + msg)) if getCache(msg): self.robot.logger.info(self.log('命中缓存,播放缓存语音')) voice = getCache(msg) else: try: voice = self.robot.tool['tts'].tts(msg) if cache: saveCache(voice, msg) except Exception as e: self.robot.logger.error(self.log('保存缓存失败:{}'.format(e))) if completed is None: completed = lambda: self.robot.brain.doubt(msg) self.speek(voice, not cache, completed=completed) def speek(self, voice, delete=False, completed=None, volume=1): #if self.speaker == None: self.speaker = Demeter.service('sox', 'player') self.speaker.init(self) self.speaker.play(voice, delete=delete, onCompleted=completed, volume=volume) def checkSpeeker(self): return self.speaker is not None and self.speaker.is_playing() # 中断、停止 def close(self): if self.checkSpeeker(): self.speaker.stop() self.speaker = None def log(self, text): return 'Mouth:' + text