-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathindex.js
More file actions
1257 lines (1101 loc) · 50.6 KB
/
index.js
File metadata and controls
1257 lines (1101 loc) · 50.6 KB
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
const encoder = new TextEncoder();
let expiredAt = null;
let endpoint = null;
// 添加缓存相关变量
let voiceListCache = null;
let voiceListCacheTime = null;
const VOICE_CACHE_DURATION =4 *60 * 60 * 1000; // 4小时,单位毫秒
// 定义需要保留的 SSML 标签模式
const preserveTags = [
{ name: 'break', pattern: /<break\s+[^>]*\/>/g },
{ name: 'speak', pattern: /<speak>|<\/speak>/g },
{ name: 'prosody', pattern: /<prosody\s+[^>]*>|<\/prosody>/g },
{ name: 'emphasis', pattern: /<emphasis\s+[^>]*>|<\/emphasis>/g },
{ name: 'voice', pattern: /<voice\s+[^>]*>|<\/voice>/g },
{ name: 'say-as', pattern: /<say-as\s+[^>]*>|<\/say-as>/g },
{ name: 'phoneme', pattern: /<phoneme\s+[^>]*>|<\/phoneme>/g },
{ name: 'audio', pattern: /<audio\s+[^>]*>|<\/audio>/g },
{ name: 'p', pattern: /<p>|<\/p>/g },
{ name: 's', pattern: /<s>|<\/s>/g },
{ name: 'sub', pattern: /<sub\s+[^>]*>|<\/sub>/g },
{ name: 'mstts', pattern: /<mstts:[^>]*>|<\/mstts:[^>]*>/g }
];
function uuid(){
return crypto.randomUUID().replace(/-/g, '')
}
// EscapeSSML 转义 SSML 内容,但保留配置的标签
function escapeSSML(ssml) {
// 使用占位符替换标签
let placeholders = new Map();
let processedSSML = ssml;
let counter = 0;
// 处理所有配置的标签
for (const tag of preserveTags) {
processedSSML = processedSSML.replace(tag.pattern, function(match) {
const placeholder = `__SSML_PLACEHOLDER_${tag.name}_${counter++}__`;
placeholders.set(placeholder, match);
return placeholder;
});
}
// 对处理后的文本进行HTML转义
let escapedContent = escapeBasicXml(processedSSML);
// 恢复所有标签占位符
placeholders.forEach((tag, placeholder) => {
escapedContent = escapedContent.replace(placeholder, tag);
});
return escapedContent;
}
// 基本 XML 转义功能,只处理基本字符
function escapeBasicXml(unsafe) {
return unsafe.replace(/[<>&'"]/g, function (c) {
switch (c) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case '\'': return ''';
case '"': return '"';
}
});
}
async function handleRequest(request) {
const requestUrl = new URL(request.url);
const path = requestUrl.pathname;
if (path === '/tts') {
// 从请求参数获取 API 密钥
const apiKey = requestUrl.searchParams.get('api_key');
// 验证 API 密钥
if (!validateApiKey(apiKey)) {
// 改进 401 错误响应,提供更友好的错误信息
return new Response(JSON.stringify({
error: 'Unauthorized',
message: '无效的 API 密钥,请确保您提供了正确的密钥。',
status: 401
}), {
status: 401,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
}
const text = requestUrl.searchParams.get('t') || '';
const voiceName = requestUrl.searchParams.get('v') || 'zh-CN-XiaoxiaoMultilingualNeural';
const rate = Number(requestUrl.searchParams.get('r')) || 0;
const pitch = Number(requestUrl.searchParams.get('p')) || 0;
const style = requestUrl.searchParams.get('s') || 'general';
const outputFormat = requestUrl.searchParams.get('o') || 'audio-24khz-48kbitrate-mono-mp3';
const download = requestUrl.searchParams.get('d') || false;
const response = await getVoice(text, voiceName, rate, pitch, style, outputFormat, download);
return response;
}
// 添加 reader.json 路径处理
if (path === '/reader.json') {
// 从请求参数获取 API 密钥
const apiKey = requestUrl.searchParams.get('api_key');
// 验证 API 密钥
if (!validateApiKey(apiKey)) {
return new Response(JSON.stringify({
error: 'Unauthorized',
message: '无效的 API 密钥,请确保您提供了正确的密钥。',
status: 401
}), {
status: 401,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
}
// 从URL参数获取
const voice = requestUrl.searchParams.get('v') || '';
const rate = requestUrl.searchParams.get('r') || '';
const pitch = requestUrl.searchParams.get('p') || '';
const style = requestUrl.searchParams.get('s') || '';
const displayName = requestUrl.searchParams.get('n') || 'Microsoft TTS';
// 构建基本URL
const baseUrl = `${requestUrl.protocol}//${requestUrl.host}`;
// 构建URL参数
const urlParams = ["t={{java.encodeURI(speakText)}}", "r={{speakSpeed*4}}"];
// 只有有值的参数才添加
if (voice) {
urlParams.push(`v=${voice}`);
}
if (pitch) {
urlParams.push(`p=${pitch}`);
}
if (style) {
urlParams.push(`s=${style}`);
}
// 只有配置了API密钥且请求提供了api_key参数时才添加
if (API_KEY && apiKey) {
urlParams.push(`api_key=${apiKey}`);
}
const url = `${baseUrl}/tts?${urlParams.join('&')}`;
// 返回 reader 响应
return new Response(JSON.stringify({
id: Date.now(),
name: displayName,
url: url
}), {
status: 200,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
}
// 添加 ifreetime.json 路径处理
if (path === '/ifreetime.json') {
// 从请求参数获取 API 密钥
const apiKey = requestUrl.searchParams.get('api_key');
// 验证 API 密钥
if (!validateApiKey(apiKey)) {
return new Response(JSON.stringify({
error: 'Unauthorized',
message: '无效的 API 密钥,请确保您提供了正确的密钥。',
status: 401
}), {
status: 401,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
}
// 从URL参数获取
const voice = requestUrl.searchParams.get('v') || '';
const rate = requestUrl.searchParams.get('r') || '';
const pitch = requestUrl.searchParams.get('p') || '';
const style = requestUrl.searchParams.get('s') || '';
const displayName = requestUrl.searchParams.get('n') || 'Microsoft TTS';
// 构建基本URL
const baseUrl = `${requestUrl.protocol}//${requestUrl.host}`;
const url = `${baseUrl}/tts`;
// 生成随机的唯一ID
const ttsConfigID = crypto.randomUUID();
// 构建请求参数
const params = {
"t": "%@", // %@ 是 IFreeTime 中的文本占位符
"v": voice,
"r": rate,
"p": pitch,
"s": style
};
// 只有配置了API密钥且请求提供了api_key参数时才添加
if (API_KEY && apiKey) {
params["api_key"] = apiKey;
}
// 构建响应
const response = {
loginUrl: "",
maxWordCount: "",
customRules: {},
ttsConfigGroup: "Azure",
_TTSName: displayName,
_ClassName: "JxdAdvCustomTTS",
_TTSConfigID: ttsConfigID,
httpConfigs: {
useCookies: 1,
headers: {}
},
voiceList: [],
ttsHandles: [
{
paramsEx: "",
processType: 1,
maxPageCount: 1,
nextPageMethod: 1,
method: 1,
requestByWebView: 0,
parser: {},
nextPageParams: {},
url: url,
params: params,
httpConfigs: {
useCookies: 1,
headers: {}
}
}
]
};
// 返回 IFreeTime 响应
return new Response(JSON.stringify(response), {
status: 200,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
}
// 添加 OpenAI 兼容接口路由
if (path === '/v1/audio/speech' || path === '/audio/speech') {
return await handleOpenAITTS(request);
}
if(path === '/voices') {
const l = (requestUrl.searchParams.get('l') || '').toLowerCase();
const f = requestUrl.searchParams.get('f');
let response = await voiceList();
if(l.length > 0) {
response = response.filter(item => item.Locale.toLowerCase().includes(l));
}
return new Response(JSON.stringify(response), {
headers:{
'Content-Type': 'application/json; charset=utf-8'
}
});
}
const baseUrl = request.url.split('://')[0] + "://" +requestUrl.host;
return new Response(`
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Microsoft TTS API</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'ms-blue': '#0078d4',
'ms-dark-blue': '#005a9e',
}
}
}
}
</script>
</head>
<body class="bg-gray-50 text-gray-800">
<!-- 导航栏 -->
<nav class="bg-ms-blue shadow-2xl">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<svg class="w-8 h-8 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
</svg>
<span class="ml-2 font-bold text-white text-xl">Microsoft TTS API</span>
</div>
</div>
</div>
</nav>
<!-- 主内容 -->
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
<div class="flex flex-col lg:flex-row gap-8">
<!-- 语音转换 -->
<div class="lg:w-3/4 mx-auto">
<div class="bg-white overflow-hidden shadow rounded-lg divide-y divide-gray-200">
<div class="px-4 py-5 sm:px-6">
<h2 class="text-lg font-medium text-gray-900">在线文本转语音</h2>
<p class="mt-1 text-sm text-gray-500">输入文本并选择语音进行转换</p>
</div>
<div class="px-4 py-5 sm:p-6">
<form id="ttsForm" class="space-y-6">
<!-- 添加错误提示区域 -->
<div id="apiErrorAlert" class="rounded-md bg-red-50 p-4" style="display: none;">
<div class="flex">
<div class="ml-3">
<h3 class="text-sm font-medium text-red-800" id="apiErrorTitle">错误</h3>
<div class="mt-2 text-sm text-red-700">
<p id="apiErrorMessage"></p>
</div>
</div>
</div>
</div>
<div>
<label for="apiKey" class="block text-sm font-medium text-gray-700">API Key</label>
<div class="mt-1 flex rounded-md shadow-sm">
<div id="apiKeyInputGroup" class="flex-grow flex relative">
<input type="password" id="apiKey" name="apiKey" required
class="block w-full shadow-sm sm:text-sm border-gray-300 rounded-md focus:ring-ms-blue focus:border-ms-blue"
placeholder="输入API Key" />
<button type="button" id="toggleApiKeyVisibility" class="absolute inset-y-0 right-0 px-3 flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 06 0z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
</button>
</div>
<button type="button" id="saveApiKey" class="ml-2 inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-white bg-ms-blue hover:bg-ms-dark-blue focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-ms-blue">
保存
</button>
</div>
<div id="savedApiKeyInfo" style="display:none;" class="mt-2 flex items-center justify-between">
<span class="text-sm text-green-600 flex items-center">
API Key 已保存
</span>
<button type="button" id="editApiKey" class="text-sm text-ms-blue hover:text-ms-dark-blue">
编辑
</button>
</div>
</div>
<div>
<label for="text" class="block text-sm font-medium text-gray-700">输入文本</label>
<textarea id="text" name="text" rows="4" required
class="mt-1 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md focus:ring-ms-blue focus:border-ms-blue"
placeholder="请输入要转换的文本"></textarea>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label for="voice" class="block text-sm font-medium text-gray-700">选择语音</label>
<select id="voice" name="voice"
class="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-ms-blue focus:border-ms-blue sm:text-sm">
</select>
</div>
<div>
<label for="style" class="block text-sm font-medium text-gray-700">语音风格</label>
<select id="style" name="style"
class="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-ms-blue focus:border-ms-blue sm:text-sm">
<option value="general" selected>标准</option>
<option value="advertisement_upbeat">广告热情</option>
<option value="affectionate">亲切</option>
<option value="angry">愤怒</option>
<option value="assistant">助理</option>
<option value="calm">平静</option>
<option value="chat">随意</option>
<option value="cheerful">愉快</option>
<option value="customerservice">客服</option>
<option value="depressed">沮丧</option>
<option value="disgruntled">不满</option>
<option value="documentary-narration">纪录片解说</option>
<option value="embarrassed">尴尬</option>
<option value="empathetic">共情</option>
<option value="envious">羡慕</option>
<option value="excited">兴奋</option>
<option value="fearful">恐惧</option>
<option value="friendly">友好</option>
<option value="gentle">温柔</option>
<option value="hopeful">希望</option>
<option value="lyrical">抒情</option>
<option value="narration-professional">专业叙述</option>
<option value="narration-relaxed">轻松叙述</option>
<option value="newscast">新闻播报</option>
<option value="newscast-casual">随意新闻</option>
<option value="newscast-formal">正式新闻</option>
<option value="poetry-reading">诗朗诵</option>
<option value="sad">悲伤</option>
<option value="serious">严肃</option>
<option value="shouting">大喊</option>
<option value="sports_commentary">体育解说</option>
<option value="sports_commentary_excited">激动体育解说</option>
<option value="whispering">低语</option>
<option value="terrified">恐慌</option>
<option value="unfriendly">冷漠</option>
</select>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label for="rate" class="block text-sm font-medium text-gray-700">语速调整</label>
<div class="flex items-center mt-2">
<span id="rateValue" class="w-8 text-sm text-gray-500">0</span>
<input type="range" id="rate" name="rate" min="-100" max="100" value="0"
class="mt-1 block w-full" oninput="document.getElementById('rateValue').textContent=this.value" />
</div>
</div>
<div>
<label for="pitch" class="block text-sm font-medium text-gray-700">音调调整</label>
<div class="flex items-center mt-2">
<span id="pitchValue" class="w-8 text-sm text-gray-500">0</span>
<input type="range" id="pitch" name="pitch" min="-100" max="100" value="0"
class="mt-1 block w-full" oninput="document.getElementById('pitchValue').textContent=this.value" />
</div>
</div>
</div>
<div class="flex flex-col sm:flex-row gap-3">
<button type="submit"
class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-ms-blue hover:bg-ms-dark-blue focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-ms-blue">
生成语音
</button>
<button type="button" id="downloadBtn" style="display:none;"
class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
下载音频
</button>
<button type="button" id="getReaderLinkBtn"
class="inline-flex justify-center py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-ms-blue">
导入阅读
</button>
<button type="button" id="getIFreeTimeLinkBtn"
class="inline-flex justify-center py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-ms-blue">
导入爱阅记
</button>
</div>
<div id="voiceLoadError" role="alert" class="mt-4 rounded-md bg-red-50 p-4" style="display: none;">
<div class="flex">
<div class="flex-shrink-0">
<svg class="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M10 18a8 8 100-16 8 8 000 16zM8.707 7.293a1 1 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 101.414 1.414L10 11.414l1.293-1.293a1 1 001.414-1.414L11.414 10l1.293-1.293a1 1 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
</div>
<div class="ml-3">
<h3 class="text-sm font-medium text-red-800">无法加载语音列表</h3>
<div class="mt-2 text-sm text-red-700">
<p>显示默认语音列表。请检查网络连接或稍后再试。</p>
</div>
</div>
</div>
</div>
</form>
<div id="audioContainer" class="mt-6 rounded-md bg-gray-50 p-4 border border-gray-200" style="display: none;">
<audio id="audioPlayer" controls class="w-full"></audio>
</div>
</div>
</div>
</div>
</div>
</main>
<!-- 页脚 -->
<footer class="bg-gray-100 border-t border-gray-200">
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
<div class="flex justify-center items-center">
<p class="text-gray-500 text-sm">© ${new Date().getFullYear()} TTS
<a href="https://github.com/zuoban/tts" target="_blank" rel="noopener noreferrer"
class="inline-flex items-center text-gray-500 hover:text-gray-700 text-sm">
<svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M10 0C4.477 0 0 4.484 0 10.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0110 4.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.31.678.921.678 1.856 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0020 10.017C20 4.484 15.522 0 10 0z" clip-rule="evenodd"></path>
</svg>
</a>
</p>
</div>
</div>
</footer>
<script>
// 存储所有语音数据
let allVoices = [];
// 在表单提交事件监听器之前添加语音选择变更事件监听
document.addEventListener('DOMContentLoaded', function() {
// 添加对语音选择变化的监听
document.getElementById('voice').addEventListener('change', function() {
updateStyleOptions(this.value);
});
// 添加获取Reader链接按钮的事件监听
document.getElementById('getReaderLinkBtn').addEventListener('click', function() {
const apiKey = document.getElementById('apiKey').value || localStorage.getItem('tts_api_key') || '';
const voice = document.getElementById('voice').value;
const rate = document.getElementById('rate').value;
const pitch = document.getElementById('pitch').value;
const style = document.getElementById('style').value;
const displayName = document.getElementById('voice').options[document.getElementById('voice').selectedIndex].text || '微软TTS';
// 保存当前设置到localStorage
saveFormValuesToLocalStorage(voice, rate, pitch, style, document.getElementById('text').value);
// 构建URL参数
const params = new URLSearchParams();
if (apiKey) params.append('api_key', apiKey);
if (voice) params.append('v', voice);
if (rate) params.append('r', rate);
if (pitch) params.append('p', pitch);
if (style) params.append('s', style);
params.append('n', displayName);
// 打开新标签页
window.open(\`\${window.location.origin}/reader.json?\${params.toString()}\`, '_blank');
});
// 添加获取IFreeTime链接按钮的事件监听
document.getElementById('getIFreeTimeLinkBtn').addEventListener('click', function() {
const apiKey = document.getElementById('apiKey').value || localStorage.getItem('tts_api_key') || '';
const voice = document.getElementById('voice').value;
const rate = document.getElementById('rate').value;
const pitch = document.getElementById('pitch').value;
const style = document.getElementById('style').value;
const displayName = document.getElementById('voice').options[document.getElementById('voice').selectedIndex].text || '微软TTS';
// 保存当前设置到localStorage
saveFormValuesToLocalStorage(voice, rate, pitch, style, document.getElementById('text').value);
// 构建URL参数
const params = new URLSearchParams();
if (apiKey) params.append('api_key', apiKey);
if (voice) params.append('v', voice);
if (rate) params.append('r', rate);
if (pitch) params.append('p', pitch);
if (style) params.append('s', style);
params.append('n', displayName);
// 打开新标签页
window.open(\`\${window.location.origin}/ifreetime.json?\${params.toString()}\`, '_blank');
});
});
document.getElementById('ttsForm').addEventListener('submit', async function(e) {
e.preventDefault();
// 隐藏先前的错误信息
document.getElementById('apiErrorAlert').style.display = 'none';
// 获取API Key (从输入框或localStorage)
const apiKey = document.getElementById('apiKey').value || localStorage.getItem('tts_api_key') || '';
const text = encodeURIComponent(document.getElementById('text').value);
const voice = document.getElementById('voice').value;
const rate = document.getElementById('rate').value;
const pitch = document.getElementById('pitch').value;
const style = document.getElementById('style').value; // 获取选择的风格
// 保存表单值到localStorage
saveFormValuesToLocalStorage(voice, rate, pitch, style, document.getElementById('text').value);
if (!text) {
showError('请输入要转换的文本', '文本内容不能为空');
return;
}
if (!apiKey) {
showError('请输入API Key', 'API密钥不能为空');
return;
}
const url = \`${baseUrl}/tts?api_key=\${apiKey}&t=\${text}&v=\${voice}&r=\${rate}&p=\${pitch}&s=\${style}\`;
try {
const response = await fetch(url);
if (!response.ok) {
// 处理错误响应
if (response.status === 401) {
try {
const errorData = await response.json();
showError('认证失败', errorData.message || '无效的API密钥,请确保您提供了正确的密钥');
} catch (e) {
showError('认证失败', '无效的API密钥,请确保您提供了正确的密钥');
}
return;
} else {
showError('请求失败');
return;
}
}
const audioPlayer = document.getElementById('audioPlayer');
audioPlayer.src = url;
audioPlayer.play();
document.getElementById('audioContainer').style.display = 'block';
document.getElementById('downloadBtn').style.display = 'inline-block';
document.getElementById('downloadBtn').onclick = function() {
const downloadUrl = url + '&d=true';
window.location.href = downloadUrl;
};
} catch (error) {
showError('生成音频失败', error.message);
}
});
// 保存表单值到localStorage的函数
function saveFormValuesToLocalStorage(voice, rate, pitch, style, text) {
localStorage.setItem('tts_voice', voice);
localStorage.setItem('tts_rate', rate);
localStorage.setItem('tts_pitch', pitch);
localStorage.setItem('tts_style', style);
localStorage.setItem('tts_text', text);
}
// 从localStorage加载表单值的函数
function loadFormValuesFromLocalStorage() {
const voice = localStorage.getItem('tts_voice');
const rate = localStorage.getItem('tts_rate');
const pitch = localStorage.getItem('tts_pitch');
const style = localStorage.getItem('tts_style');
const text = localStorage.getItem('tts_text');
// 设置语音选择(在语音列表加载完成后设置)
if (voice) {
const voiceSelect = document.getElementById('voice');
// 我们将在语音列表加载完成后设置这个值
voiceSelect.dataset.savedValue = voice;
}
// 设置语速
if (rate) {
const rateInput = document.getElementById('rate');
rateInput.value = rate;
document.getElementById('rateValue').textContent = rate;
}
// 设置音调
if (pitch) {
const pitchInput = document.getElementById('pitch');
pitchInput.value = pitch;
document.getElementById('pitchValue').textContent = pitch;
}
// 设置文本(如果有)
if (text) {
document.getElementById('text').value = text;
}
// 风格将在语音选择后设置
}
// 显示错误信息的函数
function showError(title, message) {
const errorAlert = document.getElementById('apiErrorAlert');
document.getElementById('apiErrorTitle').textContent = title;
document.getElementById('apiErrorMessage').textContent = message;
errorAlert.style.display = 'block';
// 滚动到错误信息
errorAlert.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
// 更新风格选项的函数
function updateStyleOptions(voiceName) {
const styleSelect = document.getElementById('style');
// 清空现有选项
styleSelect.innerHTML = '';
// 默认添加标准风格
const defaultOption = document.createElement('option');
defaultOption.value = 'general';
defaultOption.text = '标准';
styleSelect.appendChild(defaultOption);
// 查找选定的语音对象
const selectedVoice = allVoices.find(v => v.ShortName === voiceName);
if (selectedVoice && selectedVoice.StyleList && selectedVoice.StyleList.length > 0) {
// 对风格列表进行排序
const styles = [...selectedVoice.StyleList].sort();
// 为每个风格创建选项
styles.forEach(style => {
// 跳过已经添加的"general"
if (style.toLowerCase() === 'general') return;
const option = document.createElement('option');
option.value = style;
// 根据风格名称进行本地化显示
option.text = getStyleDisplayName(style);
styleSelect.appendChild(option);
});
}
// 添加风格选择变化事件监听器
styleSelect.addEventListener('change', function() {
localStorage.setItem('tts_style', this.value);
});
}
// 风格名称本地化显示
function getStyleDisplayName(styleName) {
const styleMap = {
'angry': '愤怒',
'cheerful': '欢快',
'sad': '悲伤',
'fearful': '恐惧',
'disgruntled': '不满',
'serious': '严肃',
'affectionate': '深情',
'gentle': '温柔',
'embarrassed': '尴尬',
'assistant': '助手',
'calm': '平静',
'chat': '聊天',
'excited': '兴奋',
'friendly': '友好',
'hopeful': '希望',
'narration-professional': '专业叙述',
'newscast': '新闻播报',
'newscast-casual': '随性新闻',
'poetry-reading': '诗歌朗诵',
'shouting': '喊叫',
'sports-commentary': '体育解说',
'whispering': '低语'
};
return styleMap[styleName.toLowerCase()] || styleName;
}
// 加载可用语音列表
async function loadVoices() {
try {
const response = await fetch('${baseUrl}/voices');
if (response.ok) {
allVoices = await response.json();
// 按语言对语音分组并排序
const zhVoices = allVoices.filter(voice => voice.Locale.startsWith('zh-'));
const enVoices = allVoices.filter(voice => voice.Locale.startsWith('en-'));
const jaVoices = allVoices.filter(voice => voice.Locale.startsWith('ja-'));
// 其他所有语言
const otherVoices = allVoices.filter(voice =>
!voice.Locale.startsWith('zh-') &&
!voice.Locale.startsWith('en-') &&
!voice.Locale.startsWith('ja-')
);
// 清空语音选择下拉框
const voiceSelect = document.getElementById('voice');
voiceSelect.innerHTML = '';
// 添加中文语音组
if(zhVoices.length > 0) {
addVoiceGroup(voiceSelect, '中文 (Chinese)', zhVoices);
}
// 添加英文语音组
if(enVoices.length > 0) {
addVoiceGroup(voiceSelect, '英文 (English)', enVoices);
}
// 添加日文语音组
if(jaVoices.length > 0) {
addVoiceGroup(voiceSelect, '日文 (Japanese)', jaVoices);
}
// 添加其他语音组
if(otherVoices.length > 0) {
addVoiceGroup(voiceSelect, '其他语言 (Other Languages)', otherVoices);
}
// 尝试恢复保存的语音选择
const savedVoice = voiceSelect.dataset.savedValue;
if (savedVoice && voiceSelect.querySelector(\`option[value="\${savedVoice}"]\`)) {
voiceSelect.value = savedVoice;
} else {
// 默认选择晓晓多语言
const defaultVoice = 'zh-CN-XiaoxiaoMultilingualNeural';
if (voiceSelect.querySelector(\`option[value="\${defaultVoice}"]\`)) {
voiceSelect.value = defaultVoice;
}
}
// 加载初始选择语音的风格选项
updateStyleOptions(voiceSelect.value);
// 尝试恢复保存的风格选择
const savedStyle = localStorage.getItem('tts_style');
if (savedStyle) {
setTimeout(() => {
const styleSelect = document.getElementById('style');
if (styleSelect.querySelector(\`option[value="\${savedStyle}"]\`)) {
styleSelect.value = savedStyle;
}
}, 100); // 给updateStyleOptions一点时间来填充选项
}
// 添加语音选择变化事件监听器,保存选择到localStorage
voiceSelect.addEventListener('change', function() {
localStorage.setItem('tts_voice', this.value);
updateStyleOptions(this.value);
});
// 添加语速变化事件监听器
document.getElementById('rate').addEventListener('change', function() {
localStorage.setItem('tts_rate', this.value);
});
// 添加音调变化事件监听器
document.getElementById('pitch').addEventListener('change', function() {
localStorage.setItem('tts_pitch', this.value);
});
// 添加文本变化事件监听器
document.getElementById('text').addEventListener('input', function() {
localStorage.setItem('tts_text', this.value);
});
} else {
console.error('获取语音列表失败:', response.status);
showDefaultVoices();
}
} catch (error) {
console.error('加载语音列表失败:', error);
showDefaultVoices();
}
}
// 添加语音组到下拉框
function addVoiceGroup(select, groupName, voices) {
const group = document.createElement('optgroup');
group.label = groupName;
// 对语音按名称排序
voices.sort((a, b) => {
const nameA = a.LocalName || a.DisplayName;
const nameB = b.LocalName || b.DisplayName;
return nameA.localeCompare(nameB);
});
voices.forEach(voice => {
const option = document.createElement('option');
option.value = voice.ShortName;
option.text = \`\${voice.LocalName || voice.DisplayName} (\${voice.Gender === 'Female' ? '女' : '男'})\`;
group.appendChild(option);
});
select.appendChild(group);
}
// 加载默认语音列表
function showDefaultVoices() {
document.getElementById('voiceLoadError').style.display = 'block';
const voiceSelect = document.getElementById('voice');
voiceSelect.innerHTML = '';
const defaultVoices = [
{ value: "zh-CN-XiaoxiaoMultilingualNeural", text: "晓晓多语言(女) - zh-CN-XiaoxiaoMultilingualNeural" },
{ value: "zh-CN-XiaoxiaoNeural", text: "晓晓(女) - zh-CN-XiaoxiaoNeural" },
{ value: "zh-CN-YunxiNeural", text: "云希(男) - zh-CN-YunxiNeural" },
{ value: "zh-CN-XiaomoNeural", text: "晓墨(女) - zh-CN-XiaomoNeural" },
{ value: "zh-CN-YunjianNeural", text: "云健(男) - zh-CN-YunjianNeural" },
{ value: "zh-CN-XiaochenNeural", text: "晓陈(儿童) - zh-CN-XiaochenNeural" },
{ value: "en-US-AriaNeural", text: "Aria(女) - en-US-AriaNeural" },
{ value: "en-US-GuyNeural", text: "Guy(男) - en-US-GuyNeural" }
];
const group = document.createElement('optgroup');
group.label = '默认语音';
defaultVoices.forEach(voice => {
const option = document.createElement('option');
option.value = voice.value;
option.text = voice.text;
group.appendChild(option);
});
voiceSelect.appendChild(group);
// 默认选择晓晓多语言
voiceSelect.value = "zh-CN-XiaoxiaoMultilingualNeural";
// 设置默认风格
const styleSelect = document.getElementById('style');
styleSelect.innerHTML = '';
const defaultOption = document.createElement('option');
defaultOption.value = 'general';
defaultOption.text = '标准';
styleSelect.appendChild(defaultOption);
}
// 页面加载完成后加载语音列表
window.onload = function() {
// 先加载保存的表单值
loadFormValuesFromLocalStorage();
// 然后加载语音列表
loadVoices();
// API Key 相关功能
const apiKeyInput = document.getElementById('apiKey');
const saveApiKeyBtn = document.getElementById('saveApiKey');
const editApiKeyBtn = document.getElementById('editApiKey');
const savedApiKeyInfo = document.getElementById('savedApiKeyInfo');
const apiKeyInputGroup = document.getElementById('apiKeyInputGroup');
const toggleApiKeyVisibilityBtn = document.getElementById('toggleApiKeyVisibility');
// 显示/隐藏API Key
toggleApiKeyVisibilityBtn.addEventListener('click', function() {
const type = apiKeyInput.getAttribute('type') === 'password' ? 'text' : 'password';
apiKeyInput.setAttribute('type', type);
// 修改图标
if (type === 'text') {
this.innerHTML = \`<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l18 18" />
</svg>\`;
} else {
this.innerHTML = \`<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 06 0z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>\`;
}
});
// 保存API Key到localStorage
saveApiKeyBtn.addEventListener('click', function() {
const apiKey = apiKeyInput.value.trim();
if (apiKey) {
localStorage.setItem('tts_api_key', apiKey);
apiKeyInputGroup.style.display = 'none';
saveApiKeyBtn.style.display = 'none';
savedApiKeyInfo.style.display = 'flex';
} else {
alert('请输入有效的API Key');
}
});
// 编辑已保存的API Key
editApiKeyBtn.addEventListener('click', function() {
apiKeyInputGroup.style.display = 'flex';
saveApiKeyBtn.style.display = 'inline-flex';
savedApiKeyInfo.style.display = 'none';
});
// 检查是否有保存的API Key
const savedApiKey = localStorage.getItem('tts_api_key');
if (savedApiKey) {
apiKeyInput.value = savedApiKey;
apiKeyInputGroup.style.display = 'none';
saveApiKeyBtn.style.display = 'none';
savedApiKeyInfo.style.display = 'flex';
}
};
</script>
</body>
</html>
`, { status: 200, headers: { 'Content-Type': 'text/html; charset=utf-8'}});
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function getEndpoint() {
const endpointUrl = 'https://dev.microsofttranslator.com/apps/endpoint?api-version=1.0';
const headers = {
'Accept-Language': 'zh-Hans',
'X-ClientVersion': '4.0.530a 5fe1dc6c',
'X-UserId': generateUserId(), // 使用随机生成的UserId
'X-HomeGeographicRegion': 'zh-Hans-CN',
'X-ClientTraceId': uuid(), // 直接使用uuid函数生成
'X-MT-Signature': await sign(endpointUrl),
'User-Agent': 'okhttp/4.5.0',
'Content-Type': 'application/json',
'Content-Length': '0',
'Accept-Encoding': 'gzip'
};