human/tts/tts_audio_handle.py

72 lines
2.0 KiB
Python
Raw Normal View History

2024-10-11 12:09:54 +00:00
#encoding = utf8
import os
import shutil
from audio import save_wav
2024-10-15 00:31:43 +00:00
from human import AudioHandler
2024-10-11 12:09:54 +00:00
2024-10-15 00:31:43 +00:00
class TTSAudioHandle(AudioHandler):
2024-10-11 12:09:54 +00:00
def __init__(self):
self._sample_rate = 16000
2024-10-14 10:20:55 +00:00
self._index = 1
2024-10-11 12:09:54 +00:00
@property
def sample_rate(self):
return self._sample_rate
@sample_rate.setter
def sample_rate(self, value):
self._sample_rate = value
2024-10-14 10:20:55 +00:00
def get_index(self):
self._index = self._index + 1
return self._index
2024-10-11 12:09:54 +00:00
class TTSAudioSplitHandle(TTSAudioHandle):
2024-10-15 00:31:43 +00:00
def __init__(self, context):
2024-10-11 12:09:54 +00:00
super().__init__()
2024-10-15 00:31:43 +00:00
self._context = context
self.sample_rate = self._context.get_audio_sample_rate()
self._chunk = self.sample_rate // self._context.get_fps()
2024-10-11 12:09:54 +00:00
2024-10-14 10:20:55 +00:00
def on_handle(self, stream, index):
2024-10-11 12:09:54 +00:00
stream_len = stream.shape[0]
idx = 0
while stream_len >= self._chunk:
2024-10-15 00:31:43 +00:00
self._context.put_audio_frame(stream[idx:idx + self._chunk])
2024-10-11 12:09:54 +00:00
stream_len -= self._chunk
idx += self._chunk
class TTSAudioSaveHandle(TTSAudioHandle):
def __init__(self):
super().__init__()
self._save_path_dir = '../temp/audio/'
self._clean()
def _clean(self):
directory = self._save_path_dir
if not os.path.exists(directory):
print(f"The directory {directory} does not exist.")
return
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
# 如果是文件,删除
if os.path.isfile(file_path):
os.remove(file_path)
print(f"Deleted file: {file_path}")
# 如果是文件夹,递归删除所有文件夹中的内容
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
print(f"Deleted directory and its contents: {file_path}")
2024-10-14 10:20:55 +00:00
def on_handle(self, stream, index):
file_name = self._save_path_dir + str(index) + '.wav'
2024-10-11 12:09:54 +00:00
save_wav(stream, file_name, self.sample_rate)