forked from Ikaros-521/AI-Vtuber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio.py
1947 lines (1575 loc) · 85.8 KB
/
audio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time, logging
import requests, re
import json, threading
import subprocess
import pygame
from queue import Queue, Empty
import edge_tts
import asyncio
from copy import deepcopy
import aiohttp
import glob
import os, random
import copy
import traceback
from elevenlabs import generate, play, set_api_key
from pydub import AudioSegment
from .common import Common
from .logger import Configure_logger
from .config import Config
from utils.audio_handle.my_tts import MY_TTS
from utils.audio_handle.audio_player import AUDIO_PLAYER
class Audio:
# 文案播放标志 0手动暂停 1临时暂停 2循环播放
copywriting_play_flag = -1
# 初始化多个pygame.mixer实例
mixer_normal = pygame.mixer
mixer_copywriting = pygame.mixer
# 全局变量用于保存恢复文案播放计时器对象
unpause_copywriting_play_timer = None
audio_player = None
# 消息列表,存储待合成音频的json数据
message_queue = []
message_queue_lock = threading.Lock()
message_queue_not_empty = threading.Condition(lock=message_queue_lock)
# 创建音频路径队列
voice_tmp_path_queue = Queue()
# # 文案单独一个线程排队播放
# only_play_copywriting_thread = None
abnormal_alarm_data = {
"platform": {
"error_count": 0
},
"llm": {
"error_count": 0
},
"tts": {
"error_count": 0
},
"svc": {
"error_count": 0
},
"visual_body": {
"error_count": 0
},
"other": {
"error_count": 0
}
}
def __init__(self, config_path, type=1):
self.config = Config(config_path)
self.common = Common()
self.my_tts = MY_TTS(config_path)
# 文案模式
if type == 2:
logging.info("文案模式的Audio初始化...")
return
# 文案单独一个线程排队播放
self.only_play_copywriting_thread = None
# 日志文件路径
file_path = "./log/log-" + self.common.get_bj_time(1) + ".txt"
Configure_logger(file_path)
# 旧版同步写法
# threading.Thread(target=self.message_queue_thread).start()
# 改异步
threading.Thread(target=lambda: asyncio.run(self.message_queue_thread())).start()
# 音频合成单独一个线程排队播放
threading.Thread(target=lambda: asyncio.run(self.only_play_audio())).start()
# self.only_play_audio_thread = threading.Thread(target=self.only_play_audio)
# self.only_play_audio_thread.start()
# 文案单独一个线程排队播放
if self.only_play_copywriting_thread == None:
# self.only_play_copywriting_thread = threading.Thread(target=lambda: asyncio.run(self.only_play_copywriting()))
self.only_play_copywriting_thread = threading.Thread(target=self.start_only_play_copywriting)
self.only_play_copywriting_thread.start()
Audio.audio_player = AUDIO_PLAYER(self.config.get("audio_player"))
# 判断等待合成和已经合成的队列是否为空
def is_audio_queue_empty(self):
"""判断等待合成和已经合成的队列是否为空
Returns:
int: 0 都不为空 | 1 message_queue 为空 | 2 voice_tmp_path_queue 为空 | 3 message_queue和voice_tmp_path_queue 为空 |
4 mixer_normal 不在播放 | 5 message_queue 为空、mixer_normal 不在播放 | 6 voice_tmp_path_queue 为空、mixer_normal 不在播放 |
7 message_queue和voice_tmp_path_queue 为空、mixer_normal 不在播放 | 8 mixer_copywriting 不在播放 | 9 message_queue 为空、mixer_copywriting 不在播放 |
10 voice_tmp_path_queue 为空、mixer_copywriting 不在播放 | 11 message_queue和voice_tmp_path_queue 为空、mixer_copywriting 不在播放 |
12 message_queue 为空、voice_tmp_path_queue 为空、mixer_normal 不在播放 | 13 message_queue 为空、voice_tmp_path_queue 为空、mixer_copywriting 不在播放 |
14 voice_tmp_path_queue为空、mixer_normal 不在播放、mixer_copywriting 不在播放 | 15 message_queue和voice_tmp_path_queue 为空、mixer_normal 不在播放、mixer_copywriting 不在播放 |
"""
flag = 0
# 判断队列是否为空
if len(Audio.message_queue) == 0:
flag += 1
if Audio.voice_tmp_path_queue.empty():
flag += 2
# 检查mixer_normal是否正在播放
if not Audio.mixer_normal.music.get_busy():
flag += 4
# 检查mixer_copywriting是否正在播放
if not Audio.mixer_copywriting.music.get_busy():
flag += 8
return flag
# 重载config
def reload_config(self, config_path):
self.config = Config(config_path)
self.my_tts = MY_TTS(config_path)
# 从指定文件夹中搜索指定文件,返回搜索到的文件路径
def search_files(self, root_dir, target_file="", ignore_extension=False):
matched_files = []
# 如果忽略扩展名,只取目标文件的基本名
target_for_comparison = os.path.splitext(target_file)[0] if ignore_extension else target_file
for root, dirs, files in os.walk(root_dir):
for file in files:
# 根据 ignore_extension 判断是否要去除扩展名后再比较
file_to_compare = os.path.splitext(file)[0] if ignore_extension else file
if file_to_compare == target_for_comparison:
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, root_dir)
relative_path = relative_path.replace("\\", "/") # 将反斜杠替换为斜杠
matched_files.append(relative_path)
return matched_files
# 获取本地音频文件夹内所有的音频文件名
def get_dir_audios_filename(self, audio_path, type=0):
"""获取本地音频文件夹内所有的音频文件名
Args:
audio_path (str): 音频文件路径
type (int, 可选): 区分返回内容,0返回完整文件名,1返回文件名不含拓展名. 默认是0
Returns:
list: 文件名列表
"""
try:
# 使用 os.walk 遍历文件夹及其子文件夹
audio_files = []
for root, dirs, files in os.walk(audio_path):
for file in files:
if file.endswith(('.mp3', '.wav', '.MP3', '.WAV', '.flac', '.aac', '.ogg', '.m4a')):
audio_files.append(os.path.join(root, file))
# 提取文件名或保留完整文件名
if type == 1:
# 只返回文件名不含拓展名
file_names = [os.path.splitext(os.path.basename(file))[0] for file in audio_files]
else:
# 返回完整文件名
file_names = [os.path.basename(file) for file in audio_files]
# 保留子文件夹路径
# file_names = [os.path.relpath(file, audio_path) for file in audio_files]
logging.debug("获取到本地音频文件名列表如下:")
logging.debug(file_names)
return file_names
except Exception as e:
logging.error(traceback.format_exc())
return None
# 音频合成消息队列线程
async def message_queue_thread(self):
logging.info("创建音频合成消息队列线程")
while True: # 无限循环,直到队列为空时退出
try:
# 获取线程锁,避免同时操作
with Audio.message_queue_lock:
while not Audio.message_queue:
# 消费者在消费完一个消息后,如果列表为空,则调用wait()方法阻塞自己,直到有新消息到来
Audio.message_queue_not_empty.wait() # 阻塞直到列表非空
message = Audio.message_queue.pop(0)
logging.debug(message)
await self.my_play_voice(message)
# message = Audio.message_queue.get(block=True)
# logging.debug(message)
# await self.my_play_voice(message)
# Audio.message_queue.task_done()
# 加个延时 降低点edge-tts的压力
# await asyncio.sleep(0.5)
except Exception as e:
logging.error(traceback.format_exc())
# 调用so-vits-svc的api
async def so_vits_svc_api(self, audio_path=""):
try:
url = f"{self.config.get('so_vits_svc', 'api_ip_port')}/wav2wav"
params = {
"audio_path": audio_path,
"tran": self.config.get("so_vits_svc", "tran"),
"spk": self.config.get("so_vits_svc", "spk"),
"wav_format": self.config.get("so_vits_svc", "wav_format")
}
# logging.info(params)
async with aiohttp.ClientSession() as session:
async with session.post(url, data=params) as response:
if response.status == 200:
file_name = 'so-vits-svc_' + self.common.get_bj_time(4) + '.wav'
voice_tmp_path = self.common.get_new_audio_path(self.config.get("play_audio", "out_path"), file_name)
with open(voice_tmp_path, 'wb') as file:
file.write(await response.read())
logging.debug(f"so-vits-svc转换完成,音频保存在:{voice_tmp_path}")
return voice_tmp_path
else:
logging.error(await response.text())
return None
except Exception as e:
logging.error(traceback.format_exc())
return None
# 调用ddsp_svc的api
async def ddsp_svc_api(self, audio_path=""):
try:
url = f"{self.config.get('ddsp_svc', 'api_ip_port')}/voiceChangeModel"
# 读取音频文件
with open(audio_path, "rb") as file:
audio_file = file.read()
data = aiohttp.FormData()
data.add_field('sample', audio_file)
data.add_field('fSafePrefixPadLength', str(self.config.get('ddsp_svc', 'fSafePrefixPadLength')))
data.add_field('fPitchChange', str(self.config.get('ddsp_svc', 'fPitchChange')))
data.add_field('sSpeakId', str(self.config.get('ddsp_svc', 'sSpeakId')))
data.add_field('sampleRate', str(self.config.get('ddsp_svc', 'sampleRate')))
async with aiohttp.ClientSession() as session:
async with session.post(url, data=data) as response:
# 检查响应状态
if response.status == 200:
file_name = 'ddsp-svc_' + self.common.get_bj_time(4) + '.wav'
voice_tmp_path = self.common.get_new_audio_path(self.config.get("play_audio", "out_path"), file_name)
with open(voice_tmp_path, 'wb') as file:
file.write(await response.read())
logging.debug(f"ddsp-svc转换完成,音频保存在:{voice_tmp_path}")
return voice_tmp_path
else:
logging.error(f"请求ddsp-svc失败,状态码:{response.status}")
return None
except Exception as e:
logging.error(traceback.format_exc())
return None
# 调用xuniren的api
async def xuniren_api(self, audio_path=""):
try:
url = f"{self.config.get('xuniren', 'api_ip_port')}/audio_to_video?file_path={os.path.abspath(audio_path)}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
# 检查响应状态
if response.status == 200:
logging.info(f"xuniren合成完成")
return True
else:
logging.error(f"xuniren合成失败,状态码:{response.status}")
return False
except Exception as e:
logging.error(traceback.format_exc())
return False
# 调用EasyAIVtuber的api
async def EasyAIVtuber_api(self, audio_path=""):
try:
from urllib.parse import urljoin
url = urljoin(self.config.get('EasyAIVtuber', 'api_ip_port'), "/alive")
data = {
"type": "speak", # 说话动作
"speech_path": os.path.abspath(audio_path)
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=data) as response:
# 检查响应状态
if response.status == 200:
# 使用await等待异步获取JSON响应
json_response = await response.json()
logging.info(f"EasyAIVtuber发送成功,返回:{json_response['status']}")
return True
else:
logging.error(f"EasyAIVtuber发送失败,状态码:{response.status}")
return False
except Exception as e:
logging.error(traceback.format_exc())
return False
# 调用digital_human_video_player的api
async def digital_human_video_player_api(self, audio_path=""):
try:
from urllib.parse import urljoin
url = urljoin(self.config.get('digital_human_video_player', 'api_ip_port'), "/show")
data = {
"type": self.config.get('digital_human_video_player', 'type'),
"audio_path": os.path.abspath(audio_path),
"insert_index": -1
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=data) as response:
# 检查响应状态
if response.status == 200:
# 使用await等待异步获取JSON响应
json_response = await response.json()
logging.info(f"digital_human_video_player发送成功,返回:{json_response['message']}")
return True
else:
logging.error(f"digital_human_video_player发送失败,状态码:{response.status}")
return False
except Exception as e:
logging.error(traceback.format_exc())
return False
# 数据根据优先级排队插入待合成音频队列
def data_priority_insert(self, audio_json):
"""
数据根据优先级排队插入待合成音频队列
type目前有
reread_top_priority 最高优先级-复读
comment 弹幕
local_qa_audio 本地问答音频
song 歌曲
reread 复读
key_mapping 按键映射
integral 积分
read_comment 念弹幕
gift 礼物
entrance 用户入场
follow 用户关注
schedule 定时任务
idle_time_task 闲时任务
abnormal_alarm 异常报警
image_recognition_schedule 图像识别定时任务
trends_copywriting 动态文案
"""
logging.debug(f"message_queue: {Audio.message_queue}")
logging.debug(f"audio_json: {audio_json}")
# 定义 type 到优先级的映射,相同优先级的 type 映射到相同的值,值越大优先级越高
priority_mapping = self.config.get("filter", "priority_mapping")
def get_priority_level(audio_json):
"""根据 audio_json 的 'type' 键返回优先级,未定义的 type 或缺失 'type' 键将返回 None"""
# 检查 audio_json 是否包含 'type' 键且该键的值在 priority_mapping 中
audio_type = audio_json.get("type")
return priority_mapping.get(audio_type, None)
# 查找插入位置
new_data_priority = get_priority_level(audio_json)
logging.info(f"优先级: {new_data_priority}")
# 如果新数据没有 'type' 键或其类型不在 priority_mapping 中,直接插入到末尾
if new_data_priority is None:
insert_position = len(Audio.message_queue)
else:
insert_position = 0 # 默认插入到列表开头
# 从列表的最后一个元素开始,向前遍历列表,直到第一个元素
for i in range(len(Audio.message_queue) - 1, -1, -1):
item_priority = int(get_priority_level(Audio.message_queue[i]))
# 确保比较时排除未定义类型的元素
if item_priority is not None and item_priority >= new_data_priority:
# 如果找到一个元素,其优先级小于或等于新数据,则将新数据插入到此元素之后
insert_position = i + 1
break
logging.debug(f"insert_position={insert_position}")
# 数据队列数据量超长判断,插入位置索引大于最大数,则说明优先级低与队列中已存在数据,丢弃数据
if insert_position >= int(self.config.get("filter", "message_queue_max_len")):
logging.info(f"message_queue 已满,数据丢弃:【{audio_json['content']}】")
return {"code": 1, "msg": f"message_queue 已满,数据丢弃:【{audio_json['content']}】"}
# 获取线程锁,避免同时操作
with Audio.message_queue_lock:
# 在计算出的位置插入新数据
Audio.message_queue.insert(insert_position, audio_json)
# 生产者通过notify()通知消费者列表中有新的消息
Audio.message_queue_not_empty.notify()
return {"code": 200, "msg": f"数据已插入到位置 {insert_position}"}
# 音频合成(edge-tts / vits_fast)并播放
def audio_synthesis(self, message):
try:
logging.debug(message)
# 判断是否是点歌模式
if message['type'] == "song":
# 拼接json数据,存入队列
data_json = {
"type": message['type'],
"tts_type": "none",
"voice_path": message['content'],
"content": message["content"]
}
if "insert_index" in data_json:
data_json["insert_index"] = message["insert_index"]
# 是否开启了音频播放
if self.config.get("play_audio", "enable"):
# Audio.voice_tmp_path_queue.put(data_json)
self.data_priority_insert(data_json)
return
# 异常报警
elif message['type'] == "abnormal_alarm":
# 拼接json数据,存入队列
data_json = {
"type": message['type'],
"tts_type": "none",
"voice_path": message['content'],
"content": message["content"]
}
if "insert_index" in data_json:
data_json["insert_index"] = message["insert_index"]
# 是否开启了音频播放
if self.config.get("play_audio", "enable"):
# Audio.voice_tmp_path_queue.put(data_json)
self.data_priority_insert(data_json)
return
# 是否为本地问答音频
elif message['type'] == "local_qa_audio":
# 拼接json数据,存入队列
data_json = {
"type": message['type'],
"tts_type": "none",
"voice_path": message['file_path'],
"content": message["content"]
}
if "insert_index" in data_json:
data_json["insert_index"] = message["insert_index"]
# 回复时是否念用户名字
if self.config.get("read_username", "enable"):
# 由于线程是独立的,所以回复音频的合成会慢于本地音频直接播放,所以以倒述的形式回复
tmp_message = deepcopy(message)
tmp_message['type'] = "reply"
tmp_message['content'] = random.choice(self.config.get("read_username", "reply_after"))
if "{username}" in tmp_message['content']:
tmp_message['content'] = tmp_message['content'].format(username=message['username'][:self.config.get("read_username", "username_max_len")])
logging.info(f"tmp_message={tmp_message}")
self.data_priority_insert(tmp_message)
# else:
# logging.info(f"message={message}")
# self.data_priority_insert(message)
# 是否开启了音频播放
if self.config.get("play_audio", "enable"):
# Audio.voice_tmp_path_queue.put(data_json)
self.data_priority_insert(data_json)
return
# 是否为助播-本地问答音频
elif message['type'] == "assistant_anchor_audio":
# 拼接json数据,存入队列
data_json = {
"type": message['type'],
"tts_type": "none",
"voice_path": message['file_path'],
"content": message["content"]
}
if "insert_index" in data_json:
data_json["insert_index"] = message["insert_index"]
# 是否开启了音频播放
if self.config.get("play_audio", "enable"):
# Audio.voice_tmp_path_queue.put(data_json)
self.data_priority_insert(data_json)
return
# 只有信息类型是 弹幕,才会进行念用户名
elif message['type'] == "comment":
# 回复时是否念用户名字
if self.config.get("read_username", "enable"):
tmp_message = deepcopy(message)
tmp_message['type'] = "reply"
tmp_message['content'] = random.choice(self.config.get("read_username", "reply_before"))
if "{username}" in tmp_message['content']:
# 将用户名中特殊字符替换为空
message['username'] = self.common.replace_special_characters(message['username'], "!!@#¥$%^&*_-+/——=()()【】}|{:;<>~`\\")
tmp_message['content'] = tmp_message['content'].format(username=message['username'][:self.config.get("read_username", "username_max_len")])
self.data_priority_insert(tmp_message)
# 闲时任务
elif message['type'] == "idle_time_task":
if message['content_type'] in ["comment", "reread"]:
pass
elif message['content_type'] == "local_audio":
# 拼接json数据,存入队列
data_json = {
"type": message['type'],
"tts_type": "none",
"voice_path": message['file_path'],
"content": message["content"]
}
if "insert_index" in data_json:
data_json["insert_index"] = message["insert_index"]
# Audio.voice_tmp_path_queue.put(data_json)
self.data_priority_insert(data_json)
return
# 是否语句切分
if self.config.get("play_audio", "text_split_enable"):
sentences = self.common.split_sentences(message['content'])
for s in sentences:
message_copy = deepcopy(message) # 创建 message 的副本
message_copy["content"] = s # 修改副本的 content
logging.debug(f"s={s}")
if not self.common.is_all_space_and_punct(s):
self.data_priority_insert(message_copy) # 将副本放入队列中
else:
self.data_priority_insert(message)
# 单独开线程播放
# threading.Thread(target=self.my_play_voice, args=(type, data, config, content,)).start()
except Exception as e:
logging.error(traceback.format_exc())
return
# 音频变声 so-vits-svc + ddsp
async def voice_change(self, voice_tmp_path):
"""音频变声 so-vits-svc + ddsp
Args:
voice_tmp_path (str): 待变声音频路径
Returns:
str: 变声后的音频路径
"""
# 转换为绝对路径
voice_tmp_path = os.path.abspath(voice_tmp_path)
# 是否启用ddsp-svc来变声
if True == self.config.get("ddsp_svc", "enable"):
voice_tmp_path = await self.ddsp_svc_api(audio_path=voice_tmp_path)
if voice_tmp_path:
logging.info(f"ddsp-svc合成成功,输出到={voice_tmp_path}")
else:
logging.error(f"ddsp-svc合成失败,请检查配置")
self.abnormal_alarm_handle("svc")
return None
# 转换为绝对路径
voice_tmp_path = os.path.abspath(voice_tmp_path)
# 是否启用so-vits-svc来变声
if True == self.config.get("so_vits_svc", "enable"):
voice_tmp_path = await self.so_vits_svc_api(audio_path=voice_tmp_path)
if voice_tmp_path:
logging.info(f"so_vits_svc合成成功,输出到={voice_tmp_path}")
else:
logging.error(f"so_vits_svc合成失败,请检查配置")
self.abnormal_alarm_handle("svc")
return None
return voice_tmp_path
# 根据本地配置,使用TTS进行音频合成,返回相关数据
async def tts_handle(self, message):
"""根据本地配置,使用TTS进行音频合成,返回相关数据
Args:
message (dict): json数据,含tts配置,tts类型
例如:
{
'type': 'reread',
'tts_type': 'gpt_sovits',
'data': {'type': 'api', 'ws_ip_port': 'ws://localhost:9872/queue/join', 'api_ip_port': 'http://127.0.0.1:9880', 'ref_audio_path': 'F:\\\\GPT-SoVITS\\\\raws\\\\ikaros\\\\21.wav', 'prompt_text': 'マスター、どうりょくろか、いいえ、なんでもありません', 'prompt_language': '日文', 'language': '自动识别', 'cut': '凑四句一切', 'gpt_model_path': 'F:\\GPT-SoVITS\\GPT_weights\\ikaros-e15.ckpt', 'sovits_model_path': 'F:\\GPT-SoVITS\\SoVITS_weights\\ikaros_e8_s280.pth', 'webtts': {'api_ip_port': 'http://127.0.0.1:8080', 'spk': 'sanyueqi', 'lang': 'zh', 'speed': '1.0', 'emotion': '正常'}},
'config': {
'before_must_str': [], 'after_must_str': [], 'before_filter_str': ['#'], 'after_filter_str': ['#'],
'badwords': {'enable': True, 'discard': False, 'path': 'data/badwords.txt', 'bad_pinyin_path': 'data/违禁拼音.txt', 'replace': '*'},
'emoji': False, 'max_len': 80, 'max_char_len': 200,
'comment_forget_duration': 1.0, 'comment_forget_reserve_num': 1, 'gift_forget_duration': 5.0, 'gift_forget_reserve_num': 1, 'entrance_forget_duration': 5.0, 'entrance_forget_reserve_num': 2, 'follow_forget_duration': 3.0, 'follow_forget_reserve_num': 1, 'talk_forget_duration': 0.1, 'talk_forget_reserve_num': 1, 'schedule_forget_duration': 0.1, 'schedule_forget_reserve_num': 1, 'idle_time_task_forget_duration': 0.1, 'idle_time_task_forget_reserve_num': 1, 'image_recognition_schedule_forget_duration': 0.1, 'image_recognition_schedule_forget_reserve_num': 1},
'username': '主人',
'content': '你好'
}
Returns:
dict: json数据,含tts配置,tts类型,合成结果等信息
"""
# 区分TTS类型
try:
logging.debug(f"message={message}")
if message["tts_type"] == "vits":
# 语言检测
language = self.common.lang_check(message["content"])
logging.debug(f"message['content']={message['content']}")
# 自定义语言名称(需要匹配请求解析)
language_name_dict = {"en": "英文", "zh": "中文", "jp": "日文"}
if language in language_name_dict:
language = language_name_dict[language]
else:
language = "自动" # 无法识别出语言代码时的默认值
# logging.info("language=" + language)
data = {
"type": message["data"]["type"],
"api_ip_port": message["data"]["api_ip_port"],
"id": message["data"]["id"],
"format": message["data"]["format"],
"lang": language,
"length": message["data"]["length"],
"noise": message["data"]["noise"],
"noisew": message["data"]["noisew"],
"max": message["data"]["max"],
"sdp_radio": message["data"]["sdp_radio"],
"content": message["content"],
"gpt_sovits": message["data"]["gpt_sovits"],
}
# 调用接口合成语音
voice_tmp_path = await self.my_tts.vits_api(data)
elif message["tts_type"] == "bert_vits2":
if message["data"]["type"] == "hiyori":
if message["data"]["language"] == "auto":
# 自动检测语言
language = self.common.lang_check(message["content"])
logging.debug(f'language={language}')
# 自定义语言名称(需要匹配请求解析)
language_name_dict = {"en": "EN", "zh": "ZH", "ja": "JP"}
if language in language_name_dict:
language = language_name_dict[language]
else:
language = "ZH" # 无法识别出语言代码时的默认值
else:
language = message["data"]["language"]
data = {
"api_ip_port": message["data"]["api_ip_port"],
"type": message["data"]["type"],
"model_id": message["data"]["model_id"],
"speaker_name": message["data"]["speaker_name"],
"speaker_id": message["data"]["speaker_id"],
"language": language,
"length": message["data"]["length"],
"noise": message["data"]["noise"],
"noisew": message["data"]["noisew"],
"sdp_radio": message["data"]["sdp_radio"],
"auto_translate": message["data"]["auto_translate"],
"auto_split": message["data"]["auto_split"],
"emotion": message["data"]["emotion"],
"style_text": message["data"]["style_text"],
"style_weight": message["data"]["style_weight"],
"content": message["content"]
}
# 调用接口合成语音
voice_tmp_path = await self.my_tts.bert_vits2_api(data)
elif message["tts_type"] == "vits_fast":
if message["data"]["language"] == "自动识别":
# 自动检测语言
language = self.common.lang_check(message["content"])
logging.debug(f'language={language}')
# 自定义语言名称(需要匹配请求解析)
language_name_dict = {"en": "English", "zh": "简体中文", "ja": "日本語"}
if language in language_name_dict:
language = language_name_dict[language]
else:
language = "简体中文" # 无法识别出语言代码时的默认值
else:
language = message["data"]["language"]
# logging.info("language=" + language)
data = {
"api_ip_port": message["data"]["api_ip_port"],
"character": message["data"]["character"],
"speed": message["data"]["speed"],
"language": language,
"content": message["content"]
}
# 调用接口合成语音
voice_tmp_path = self.my_tts.vits_fast_api(data)
# logging.info(data_json)
elif message["tts_type"] == "edge-tts":
data = {
"content": message["content"],
"voice": message["data"]["voice"],
"rate": message["data"]["rate"],
"volume": message["data"]["volume"]
}
# 调用接口合成语音
voice_tmp_path = await self.my_tts.edge_tts_api(data)
elif message["tts_type"] == "elevenlabs":
# 如果配置了密钥就设置上0.0
if message["data"]["api_key"] != "":
set_api_key(message["data"]["api_key"])
audio = generate(
text=message["content"],
voice=message["data"]["voice"],
model=message["data"]["model"]
)
play(audio)
logging.info(f"elevenlabs合成内容:【{message['content']}】")
return
elif message["tts_type"] == "genshinvoice_top":
voice_tmp_path = await self.my_tts.genshinvoice_top_api(message["content"])
elif message["tts_type"] == "tts_ai_lab_top":
voice_tmp_path = await self.my_tts.tts_ai_lab_top_api(message["content"])
elif message["tts_type"] == "bark_gui":
data = {
"api_ip_port": message["data"]["api_ip_port"],
"spk": message["data"]["spk"],
"generation_temperature": message["data"]["generation_temperature"],
"waveform_temperature": message["data"]["waveform_temperature"],
"end_of_sentence_probability": message["data"]["end_of_sentence_probability"],
"quick_generation": message["data"]["quick_generation"],
"seed": message["data"]["seed"],
"batch_count": message["data"]["batch_count"],
"content": message["content"]
}
# 调用接口合成语音
voice_tmp_path = self.my_tts.bark_gui_api(data)
elif message["tts_type"] == "vall_e_x":
data = {
"api_ip_port": message["data"]["api_ip_port"],
"language": message["data"]["language"],
"accent": message["data"]["accent"],
"voice_preset": message["data"]["voice_preset"],
"voice_preset_file_path": message["data"]["voice_preset_file_path"],
"content": message["content"]
}
# 调用接口合成语音
voice_tmp_path = self.my_tts.vall_e_x_api(data)
elif message["tts_type"] == "openai_tts":
data = {
"type": message["data"]["type"],
"api_ip_port": message["data"]["api_ip_port"],
"model": message["data"]["model"],
"voice": message["data"]["voice"],
"api_key": message["data"]["api_key"],
"content": message["content"]
}
# 调用接口合成语音
voice_tmp_path = self.my_tts.openai_tts_api(data)
elif message["tts_type"] == "reecho_ai":
voice_tmp_path = await self.my_tts.reecho_ai_api(message["content"])
elif message["tts_type"] == "gradio_tts":
data = {
"request_parameters": message["data"]["request_parameters"],
"content": message["content"]
}
voice_tmp_path = self.my_tts.gradio_tts_api(data)
elif message["tts_type"] == "gpt_sovits":
if message["data"]["language"] == "自动识别":
# 自动检测语言
language = self.common.lang_check(message["content"])
logging.debug(f'language={language}')
# 自定义语言名称(需要匹配请求解析)
language_name_dict = {"en": "英文", "zh": "中文", "ja": "日文"}
if language in language_name_dict:
language = language_name_dict[language]
else:
language = "中文" # 无法识别出语言代码时的默认值
else:
language = message["data"]["language"]
data = {
"type": message["data"]["type"],
"gradio_ip_port": message["data"]["gradio_ip_port"],
"ws_ip_port": message["data"]["ws_ip_port"],
"api_ip_port": message["data"]["api_ip_port"],
"ref_audio_path": message["data"]["ref_audio_path"],
"prompt_text": message["data"]["prompt_text"],
"prompt_language": message["data"]["prompt_language"],
"language": language,
"cut": message["data"]["cut"],
"api_0322": message["data"]["api_0322"],
"webtts": message["data"]["webtts"],
"content": message["content"]
}
voice_tmp_path = await self.my_tts.gpt_sovits_api(data)
elif message["tts_type"] == "clone_voice":
data = {
"type": message["data"]["type"],
"api_ip_port": message["data"]["api_ip_port"],
"voice": message["data"]["voice"],
"language": message["data"]["language"],
"speed": message["data"]["speed"],
"content": message["content"]
}
voice_tmp_path = await self.my_tts.clone_voice_api(data)
elif message["tts_type"] == "azure_tts":
data = {
"subscription_key": message["data"]["subscription_key"],
"region": message["data"]["region"],
"voice_name": message["data"]["voice_name"],
"content": message["content"]
}
voice_tmp_path = self.my_tts.azure_tts_api(data)
elif message["tts_type"] == "fish_speech":
data = message["data"]
data["tts_config"]["text"] = message["content"]
voice_tmp_path = await self.my_tts.fish_speech_api(data)
elif message["tts_type"] == "none":
voice_tmp_path = None
message["result"] = {
"code": 200,
"msg": "合成成功",
"audio_path": voice_tmp_path
}
except Exception as e:
logging.error(traceback.format_exc())
message["result"] = {
"code": -1,
"msg": f"合成失败,{e}",
"audio_path": None
}
return message
# 播放音频
async def my_play_voice(self, message):
"""合成音频并插入待播放队列
Args:
message (dict): 待合成内容的json串
Returns:
bool: 合成情况
"""
logging.debug(message)
try:
# 如果是tts类型为none,暂时这类为直接播放音频,所以就丢给路径队列
if message["tts_type"] == "none":
Audio.voice_tmp_path_queue.put(message)
return
except Exception as e:
logging.error(traceback.format_exc())
return
try:
logging.debug(f"合成音频前的原始数据:{message['content']}")
message["content"] = self.common.remove_extra_words(message["content"], message["config"]["max_len"], message["config"]["max_char_len"])
# logging.info("裁剪后的合成文本:" + text)
message["content"] = message["content"].replace('\n', '。')
# 空数据就散了吧
if message["content"] == "":
return
except Exception as e:
logging.error(traceback.format_exc())
return
# 判断消息类型,再变声并封装数据发到队列 减少冗余
async def voice_change_and_put_to_queue(message, voice_tmp_path):
# 拼接json数据,存入队列
data_json = {
"type": message['type'],
"voice_path": voice_tmp_path,
"content": message["content"]
}
if "insert_index" in message:
data_json["insert_index"] = message["insert_index"]
# 区分消息类型是否是 回复xxx 并且 关闭了变声
if message["type"] == "reply" and False == self.config.get("read_username", "voice_change"):
# 是否开启了音频播放,如果没开,则不会传文件路径给播放队列
if self.config.get("play_audio", "enable"):
Audio.voice_tmp_path_queue.put(data_json)
return True
# 区分消息类型是否是 念弹幕 并且 关闭了变声
elif message["type"] == "read_comment" and False == self.config.get("read_comment", "voice_change"):
# 是否开启了音频播放,如果没开,则不会传文件路径给播放队列
if self.config.get("play_audio", "enable"):
Audio.voice_tmp_path_queue.put(data_json)
return True
voice_tmp_path = await self.voice_change(voice_tmp_path)
# 更新音频路径
data_json["voice_path"] = voice_tmp_path
# 是否开启了音频播放,如果没开,则不会传文件路径给播放队列
if self.config.get("play_audio", "enable"):
Audio.voice_tmp_path_queue.put(data_json)
return True