olivebot/utils/stream_util.py
guo zebin 4cfad5ae0f 年翻更新
- 全新ui
- 全面优化websocket逻辑,提高数字人和ui连接的稳定性及资源开销
- 全面优化唤醒逻辑,提供稳定的普通唤醒模式和前置词唤醒模式
- 优化拾音质量,支持多声道麦克风拾音
- 优化自动播放服务器的对接机制,提供稳定和兼容旧版ue工程的对接模式
- 数字人接口输出机器人表情,以适应新fay ui及单片机的数字人表情输出
- 使用更高级的音频时长计算方式,可以更精准控制音频播放完成后的逻辑
- 修复点击关闭按钮会导致程序退出的bug
- 修复没有麦克风的设备开启麦克风会出错的问题
- 为服务器主机地址提供配置项,以方便服务器部署
2024-10-26 11:34:55 +08:00

84 lines
2.2 KiB
Python

from io import BytesIO
import threading
import functools
def synchronized(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
with self.lock:
return func(self, *args, **kwargs)
return wrapper
class StreamCache:
def __init__(self, maxbytes):
self.lock = threading.Lock()
self.bytesio = BytesIO()
self.writeSeek = 0
self.readSeek = 0
self.maxbytes = maxbytes
self.idle = 0
@synchronized
def write(self, bs):
# print("写:{},{}".format(len(bs),bs), end=' ')
if self.idle >= self.maxbytes:
print("缓存区不够用")
self.bytesio.seek(self.writeSeek)
if self.writeSeek + len(bs) <= self.maxbytes:
self.bytesio.write(bs)
else:
self.bytesio.write(bs[0:self.maxbytes - self.writeSeek])
self.bytesio.seek(0)
self.bytesio.write(bs[self.maxbytes - self.writeSeek:])
self.idle += len(bs)
self.writeSeek = self.bytesio.tell()
if self.writeSeek >= self.maxbytes - 1:
self.writeSeek = 0
@synchronized
def read(self, length, exception_on_overflow = False):
if self.idle < length:
return None
# print("读:{}".format(length), end=' ')
self.bytesio.seek(self.readSeek)
if self.readSeek + length <= self.maxbytes:
bs = self.bytesio.read(length)
else:
bs = self.bytesio.read(self.maxbytes - self.readSeek)
self.bytesio.seek(0)
bs.append(self.bytesio.read(self.readSeek + length - self.maxbytes))
self.idle -= length
self.readSeek = self.bytesio.tell()
if self.readSeek >= self.maxbytes - 1:
self.readSeek = 0
return bs
@synchronized
def clear(self):
self.bytesio = BytesIO()
self.writeSeek = 0
self.readSeek = 0
self.idle = 0
if __name__ == '__main__':
streamCache = StreamCache(5)
streamCache.write(b'\x01\x02')
streamCache.write(b'\x03\x04\x00')
print(streamCache.read(2))
print(streamCache.read(3))
streamCache.write(b'\x05\x06')
print(streamCache.read(2))
print(streamCache.read(2))
print(streamCache.read(3))