voice-changer/server/sio/MMVC_Namespace.py

61 lines
2.1 KiB
Python
Raw Normal View History

2022-12-31 10:02:53 +03:00
import struct
from datetime import datetime
import numpy as np
import socketio
from voice_changer.VoiceChangerManager import VoiceChangerManager
2023-05-26 10:26:17 +03:00
import asyncio
2023-02-14 23:02:51 +03:00
2022-12-31 10:02:53 +03:00
class MMVC_Namespace(socketio.AsyncNamespace):
2023-05-06 22:18:18 +03:00
sid: int = 0
2023-05-26 10:26:17 +03:00
async def emitTo(self, data):
timestamp = 0
audio1 = np.zeros(1).astype(np.int16)
bin = struct.pack("<%sh" % len(audio1), *audio1)
perf = data
await self.emit("response", [timestamp, bin, perf], to=self.sid)
def emit_coroutine(self, data):
asyncio.run(self.emitTo(data))
2023-02-14 23:02:51 +03:00
def __init__(self, namespace: str, voiceChangerManager: VoiceChangerManager):
2022-12-31 10:02:53 +03:00
super().__init__(namespace)
self.voiceChangerManager = voiceChangerManager
2023-06-16 10:10:46 +03:00
# self.voiceChangerManager.voiceChanger.emitTo = self.emit_coroutine
self.voiceChangerManager.setEmitTo(self.emit_coroutine)
2022-12-31 10:02:53 +03:00
@classmethod
2023-02-14 23:02:51 +03:00
def get_instance(cls, voiceChangerManager: VoiceChangerManager):
2022-12-31 10:02:53 +03:00
if not hasattr(cls, "_instance"):
cls._instance = cls("/test", voiceChangerManager)
return cls._instance
def on_connect(self, sid, environ):
2023-05-06 22:18:18 +03:00
self.sid = sid
2023-06-16 10:10:46 +03:00
print("[{}] connet sid : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), sid))
2022-12-31 10:02:53 +03:00
pass
async def on_request_message(self, sid, msg):
2023-05-06 22:18:18 +03:00
self.sid = sid
2023-01-08 11:58:27 +03:00
timestamp = int(msg[0])
data = msg[1]
2023-05-06 22:18:18 +03:00
if isinstance(data, str):
print(type(data))
print(data)
2023-05-06 22:18:18 +03:00
await self.emit("response", [timestamp, 0], to=sid)
else:
2023-06-16 10:10:46 +03:00
unpackedData = np.array(struct.unpack("<%sh" % (len(data) // struct.calcsize("<h")), data)).astype(np.int16)
2023-02-21 03:17:59 +03:00
res = self.voiceChangerManager.changeVoice(unpackedData)
audio1 = res[0]
perf = res[1] if len(res) == 2 else [0, 0, 0]
2023-05-06 22:18:18 +03:00
bin = struct.pack("<%sh" % len(audio1), *audio1)
await self.emit("response", [timestamp, bin, perf], to=sid)
2022-12-31 10:02:53 +03:00
def on_disconnect(self, sid):
# print('[{}] disconnect'.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
pass