def stop(self): """ 结束识别并关闭与服务端的连接 :return: 关闭成功,返回0 关闭失败,返回-1 """ ret = 0 if self._status == Status.STATUS_STARTED: self._status = Status.STATUS_STOPPING msg_id = six.u(uuid.uuid1().hex) self._header[ Constant. HEADER_KEY_NAME] = Constant.HEADER_VALUE_TRANS_NAME_STOP self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id self._payload.clear() text = self.serialize() _log.info('sending stop cmd: ' + text) self._ws.send(text) for i in range(100): if self._status == Status.STATUS_STOPPED: break else: time.sleep(0.1) _log.debug('waite 100ms') if self._status != Status.STATUS_STOPPED: ret = -1 else: ret = 0 else: _log.error('should not stop in state %d', self._status) ret = -1 return ret
def _on_open(ws): _log.debug('websocket connected') self._status = Status.STATUS_WS_CONNECTED self._is_connected = True msg_id = six.u(uuid.uuid1().hex) self._task_id = six.u(uuid.uuid1().hex) self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_TRANS_NAME_START self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id self._header[Constant.HEADER_KEY_TASK_ID] = self._task_id text = self.serialize() _log.info('sending start cmd: ' + text) ws.send(text)
def send(self, audio_data): """ 发送语音数据到服务端,建议每次发送 1000 ~ 8000 字节 :param audio_data: 二进制音频数据 :return: 发送成功,返回0 发送失败,返回-1 """ if self._status == Status.STATUS_STARTED: self._ws.send(audio_data, opcode=websocket.ABNF.OPCODE_BINARY) return 0 elif self._status == Status.STATUS_COMPLETED_WITH_OUT_STOP: _log.info( 'the recognizer finished with VAD, no need to send data anymore!' ) return -1 else: _log.error('should not send data in state %d', self._status) return -1