-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
1590 lines (1399 loc) · 53.7 KB
/
Copy pathmain.ts
File metadata and controls
1590 lines (1399 loc) · 53.7 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
import {
App,
FileSystemAdapter,
MarkdownView,
Modal,
Notice,
Plugin,
PluginSettingTab,
Platform,
Setting,
type SettingDefinitionItem,
TFile,
} from "obsidian";
import * as childProcess from "child_process";
import * as fs from "fs";
import * as https from "https";
import * as http from "http";
import * as os from "os";
import * as path from "path";
type PlaybackState = "idle" | "loading" | "playing" | "paused" | "stopped";
type MarkdownViewWithSelectedFiles = MarkdownView & { selectedFiles?: TFile[] };
type AppWithSettings = App & { setting?: { openTabById?: (id: string) => void } };
const LOCAL_TTS_VERSION = "d84d6edb62e3e5aba94fc24930d70266a772d45a";
const LOCAL_TTS_URL = "http://127.0.0.1:51273";
interface OpenReaderSettings {
ttsctlPath?: string;
outputFolder: string;
speed: number;
playbackSpeed: number; // 播放速度(HTMLAudio.playbackRate),独立于合成速度 speed
maxChunkCharacters: number;
stripFrontmatter: boolean;
skipCodeBlocks: boolean;
keepAudioFiles: boolean;
openFolderAfterSynthesis: boolean;
// 控制器美化
showProgressBar: boolean;
enableDragToMove: boolean;
// 文本过滤
customCharsToFilter: string;
filterHtmlTags: boolean;
filterExtraWhitespace: boolean;
}
function defaultTtsctlCandidates(): string[] {
if (Platform.isMacOS) {
return [path.join(os.homedir(), "Library", "Application Support", "LocalTTS", "local-tts-service", "ttsctl.sh")];
}
if (Platform.isWin) {
const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local");
return [path.join(localAppData, "LocalTTS", "local-tts-service", "ttsctl.ps1")];
}
return [path.join(os.homedir(), ".local", "share", "local-tts-service", "ttsctl.sh")];
}
function fileExists(filePath: string): boolean {
try {
return fs.existsSync(filePath);
} catch {
return false;
}
}
const DEFAULT_SETTINGS: OpenReaderSettings = {
outputFolder: ".open-reader/audio",
speed: 1,
playbackSpeed: 1,
maxChunkCharacters: 450,
stripFrontmatter: true,
skipCodeBlocks: true,
keepAudioFiles: false,
openFolderAfterSynthesis: false,
// 控制器美化
showProgressBar: true,
enableDragToMove: true,
// 文本过滤
customCharsToFilter: "",
filterHtmlTags: true,
filterExtraWhitespace: true,
};
export default class OpenReaderPlugin extends Plugin {
settings: OpenReaderSettings;
private currentAudio: HTMLAudioElement | null = null;
private objectUrls: string[] = [];
private generatedFiles: string[] = [];
private shouldStop = false;
private statusBarEl: HTMLElement;
private controllerEl: HTMLElement | null = null;
private controllerStatusEl: HTMLElement | null = null;
private controllerTitleEl: HTMLElement | null = null;
private pauseButtonEl: HTMLButtonElement | null = null;
private resumeButtonEl: HTMLButtonElement | null = null;
private finishCurrentPlayback: (() => void) | null = null;
private activeFilePath: string | null = null; // 当前正在朗读的文件路径
private progressBarEl: HTMLElement | null = null; // 进度条元素
private progressTextEl: HTMLElement | null = null; // 进度文字元素
private fileNameEl: HTMLElement | null = null; // 文件名显示元素
private speedButtonEls: HTMLButtonElement[] = []; // 播放速度档位按钮
// 可选播放速度档位(独立于合成速度,仅作用于 HTMLAudio.playbackRate)
private static readonly PLAYBACK_SPEED_OPTIONS = [0.75, 1.0, 1.25, 1.5, 2.0];
async onload() {
await this.loadSettings();
this.statusBarEl = this.addStatusBarItem();
this.updateStatus("idle");
this.createController();
this.addRibbonIcon("volume-2", "Read note aloud or show controller", () => {
// 如果控制器已隐藏,先显示控制器
if (!this.controllerEl || !this.controllerEl.isShown()) {
this.showController();
}
void this.readActiveDocument();
});
this.addCommand({
id: "show-tts-controller",
name: "Show TTS controller",
callback: () => {
this.showController();
},
});
this.addCommand({
id: "read-selection-or-note",
name: "Read selected text or active note aloud",
callback: () => {
void this.readActiveDocument();
},
});
this.addCommand({
id: "pause-reading",
name: "Pause reading",
callback: () => this.pauseReading(),
});
this.addCommand({
id: "resume-reading",
name: "Resume reading",
callback: () => {
void this.resumeReading();
},
});
this.addCommand({
id: "stop-reading",
name: "Stop reading",
callback: () => this.stopReading(),
});
this.addCommand({
id: "test-local-tts-cli",
name: "Test Local TTS CLI",
callback: () => {
void this.testLocalTtsCli();
},
});
this.addCommand({
id: "open-tts-output-folder",
name: "Open TTS output folder",
callback: () => {
void this.openOutputFolder();
},
});
this.addSettingTab(new OpenReaderSettingTab(this.app, this));
}
onunload() {
this.stopReading(false);
this.unregisterFileCloseListener();
this.controllerEl?.remove();
}
// 页签关闭监听相关
// Obsidian 没有 file-close workspace 事件,改用 layout-change:
// 布局变化(含页签关闭/打开/拖动)时,检查是否仍有 markdown leaf 打开着
// 正在朗读的文件,若一个都不剩,说明该页签被关闭,停止播放。
private layoutChangeCallback: (() => void) | null = null;
private isSourceFileStillOpen(): boolean {
if (!this.activeFilePath) return false;
return this.app.workspace
.getLeavesOfType("markdown")
.some(
(leaf) =>
leaf.view instanceof MarkdownView &&
leaf.view.file?.path === this.activeFilePath,
);
}
private registerFileCloseListener() {
// 先取消之前的监听
this.unregisterFileCloseListener();
this.layoutChangeCallback = () => {
// 没在播放或已无目标文件时无需处理
if (!this.activeFilePath) return;
if (!this.isSourceFileStillOpen()) {
this.stopReading(true);
}
};
this.app.workspace.on("layout-change", this.layoutChangeCallback);
}
private unregisterFileCloseListener() {
if (this.layoutChangeCallback) {
this.app.workspace.off("layout-change", this.layoutChangeCallback);
this.layoutChangeCallback = null;
}
}
async loadSettings() {
const stored: unknown = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, isRecord(stored) ? stored : {});
this.removeLegacySharedFields();
}
private getTtsctlPath(): string {
const detected = this.detectTtsctlPath();
if (!detected) throw new Error("Local TTS is not installed. Open settings to install it.");
return detected;
}
detectTtsctlPath(): string | null {
return defaultTtsctlCandidates().find(fileExists) || null;
}
private removeLegacySharedFields() {
const settings = this.settings as OpenReaderSettings & {
systemName?: string;
windowsTtsctlPath?: string;
macTtsctlPath?: string;
linuxTtsctlPath?: string;
ttsctlPathsBySystem?: string;
};
delete settings.systemName;
delete settings.ttsctlPath;
delete settings.windowsTtsctlPath;
delete settings.macTtsctlPath;
delete settings.linuxTtsctlPath;
delete settings.ttsctlPathsBySystem;
}
async saveSettings() {
await this.saveData(this.settings);
}
async installLocalTts(): Promise<void> {
if (!Platform.isMacOS && !Platform.isWin) {
new Notice("Open Reader: one-click Local TTS installation currently supports macOS and Windows.");
return;
}
const approved = await confirmAction(
this.app,
"Install Local TTS?",
"Open Reader will download Local TTS from github.com/lornezhang66/local-tts-service, install Python dependencies, and download about 130 MB of speech models. Continue?",
);
if (!approved) return;
const extension = Platform.isWin ? "ps1" : "sh";
const scriptName = Platform.isWin ? "install_windows_user.ps1" : "install_macos_user.sh";
const installerPath = path.join(os.tmpdir(), `open-reader-local-tts-installer.${extension}`);
const url = `https://raw.githubusercontent.com/lornezhang66/local-tts-service/${LOCAL_TTS_VERSION}/scripts/${scriptName}`;
const installEnv = { ...process.env, LOCAL_TTS_INSTALL_REF: LOCAL_TTS_VERSION };
const progress = new Notice("Open Reader: downloading and installing Local TTS. This may take several minutes.", 0);
try {
await downloadFile(url, installerPath);
if (Platform.isWin) {
await runCommand("powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", installerPath], installEnv);
} else {
await runCommand("/bin/bash", [installerPath], installEnv);
}
if (!this.detectTtsctlPath()) throw new Error("installer finished but ttsctl was not found");
new Notice("Open Reader: Local TTS installed successfully.");
} catch (error) {
new Notice(`Open Reader: Local TTS installation failed: ${getErrorMessage(error)}`, 10000);
console.error("Local TTS installation failed", error);
} finally {
progress.hide();
await fs.promises.rm(installerPath, { force: true });
}
}
async readActiveDocument() {
if (!Platform.isDesktopApp) {
new Notice("Open Reader: Local TTS CLI is only supported on desktop.");
return;
}
const adapter = this.getFileSystemAdapter();
if (!adapter) return;
// 获取要朗读的文件路径
const sourceFile = this.getSelectedFile() || this.app.workspace.getActiveFile();
if (!sourceFile) {
new Notice("Open Reader: no file selected or active.");
return;
}
if (!this.detectTtsctlPath()) {
await this.installLocalTts();
if (!this.detectTtsctlPath()) return;
}
// 先停止上一次的播放并清理状态。
// 必须在设置新 activeFilePath / 注册监听器之前调用,
// 否则 stopReading 会把刚设置的 activeFilePath 清空、把监听器注销掉。
this.stopReading(false);
this.activeFilePath = sourceFile.path;
// 注册页签关闭监听:当该文件的页签全部关闭时自动停止播放
this.registerFileCloseListener();
const normalized = this.prepareText(await this.getTextToRead());
if (!normalized.trim()) {
new Notice("Open Reader: no readable text found.");
return;
}
this.shouldStop = false;
this.generatedFiles = [];
this.showController();
const chunks = splitTextIntoChunks(
normalized,
clampInteger(this.settings.maxChunkCharacters, 80, 4000),
);
new Notice(`Open Reader: synthesizing ${chunks.length} chunk(s) with local TTS.`);
try {
await this.ensureOutputFolder();
const ttsctlPath = this.getTtsctlPath();
let useHttp = await ensureHttpTts(ttsctlPath);
for (let index = 0; index < chunks.length; index += 1) {
if (this.shouldStop) break;
this.updateStatus("loading", index + 1, chunks.length);
const outputPath = this.getChunkOutputPath(adapter, index + 1);
const options = {
text: chunks[index],
outputPath,
speed: clampNumber(this.settings.speed, 0.5, 2),
};
if (useHttp) {
try {
await synthesizeWithHttp(options);
} catch (error) {
console.warn("Local TTS HTTP failed; falling back to ttsctl", error);
useHttp = false;
await synthesizeWithTtsctl({ ttsctlPath, ...options });
}
} else {
await synthesizeWithTtsctl({ ttsctlPath, ...options });
}
this.generatedFiles.push(outputPath);
if (this.shouldStop) break;
// 播放实际开始后才更新"正在播放"状态,
// 确保 currentAudio 已就绪、暂停按钮可点击
await this.playAudioFile(outputPath, () => {
this.updateStatus("playing", index + 1, chunks.length);
});
this.currentAudio = null;
}
if (!this.shouldStop) {
this.updateStatus("idle");
if (this.settings.openFolderAfterSynthesis) {
await this.openOutputFolder();
}
}
} catch (error) {
this.updateStatus("idle");
new Notice(`Open Reader failed: ${getErrorMessage(error)}`);
console.error("Open Reader failed", error);
} finally {
this.currentAudio = null;
this.activeFilePath = null;
this.unregisterFileCloseListener();
if (!this.settings.keepAudioFiles) {
await removeFiles(this.generatedFiles);
}
this.releaseObjectUrls();
}
}
pauseReading() {
if (!this.currentAudio || this.currentAudio.paused) return;
this.currentAudio.pause();
this.updateStatus("paused");
new Notice("已暂停");
}
async resumeReading() {
if (!this.currentAudio) return;
// 如果 audio 已暂停,恢复播放
if (this.currentAudio.paused) {
try {
await this.currentAudio.play();
this.updateStatus("playing");
new Notice("继续播放");
} catch (error) {
new Notice(`无法继续播放: ${getErrorMessage(error)}`);
}
return;
}
// 如果 audio 没有暂停但也没在播放(被阻止的情况),尝试重新播放
if (this.currentAudio.readyState >= 2) {
try {
await this.currentAudio.play();
this.updateStatus("playing");
new Notice("继续播放");
} catch (error) {
new Notice(`无法继续播放: ${getErrorMessage(error)}`);
}
} else {
new Notice("音频还未准备好,请稍后");
}
}
stopReading(showNotice = true) {
this.shouldStop = true;
if (this.currentAudio) {
this.currentAudio.pause();
this.currentAudio.removeAttribute("src");
this.currentAudio.load();
this.currentAudio = null;
}
this.finishCurrentPlayback?.();
this.finishCurrentPlayback = null;
// 清理当前文件路径和监听器
this.activeFilePath = null;
this.unregisterFileCloseListener();
this.updateStatus("stopped");
if (showNotice) {
new Notice("Open Reader: stopped.");
}
}
async testLocalTtsCli() {
if (!Platform.isDesktopApp) {
new Notice("Open Reader: Local TTS CLI is only supported on desktop.");
return;
}
const adapter = this.getFileSystemAdapter();
if (!adapter) return;
try {
await this.ensureOutputFolder();
const outputPath = this.getNamedOutputPath(adapter, "ttsctl-test.wav");
const ttsctlPath = this.getTtsctlPath();
const options = {
text: "Obsidian 本地朗读插件测试成功。",
outputPath,
speed: clampNumber(this.settings.speed, 0.5, 2),
};
if (await ensureHttpTts(ttsctlPath)) {
try {
await synthesizeWithHttp(options);
} catch {
await synthesizeWithTtsctl({ ttsctlPath, ...options });
}
} else {
await synthesizeWithTtsctl({ ttsctlPath, ...options });
}
new Notice(`Open Reader: Local TTS test passed.`);
this.showController();
try {
await this.playAudioFile(outputPath, () => {
this.updateStatus("playing");
});
} finally {
this.currentAudio = null;
this.finishCurrentPlayback = null;
this.updateStatus("idle");
this.releaseObjectUrls();
if (!this.settings.keepAudioFiles) {
await removeFiles([outputPath]);
}
}
} catch (error) {
new Notice(`Open Reader TTS test failed: ${getErrorMessage(error)}`);
console.error("Open Reader TTS test failed", error);
}
}
async openOutputFolder() {
const adapter = this.getFileSystemAdapter();
if (!adapter) return;
await this.ensureOutputFolder();
const folderPath = toNativePath(adapter.getBasePath(), normalizeVaultPath(this.settings.outputFolder));
await openPath(folderPath);
}
private getFileSystemAdapter(): FileSystemAdapter | null {
const adapter = this.app.vault.adapter;
if (!(adapter instanceof FileSystemAdapter)) {
new Notice("Open Reader: this vault adapter cannot expose local file paths.");
return null;
}
return adapter;
}
private async getTextToRead(): Promise<string> {
// 优先获取当前选中的文件(文件列表中高亮/点击的文件)
const selectedFile = this.getSelectedFile();
if (selectedFile) {
const content = await this.app.vault.read(selectedFile);
if (content.trim()) return content;
}
// 其次获取活动视图中的选中文本或全部内容
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView?.editor) {
const selectedText = markdownView.editor.getSelection();
if (selectedText.trim()) return selectedText;
const editorText = markdownView.editor.getValue();
if (editorText.trim()) return editorText;
}
// 最后获取活动文件
const activeFile = this.app.workspace.getActiveFile();
if (activeFile) return await this.app.vault.read(activeFile);
return "";
}
// 获取当前在文件列表中选中的文件
private getSelectedFile(): TFile | null {
// 尝试多种方式获取选中的文件
// 方式1: 从 workspace 的 leaf 中获取
const leaves = this.app.workspace.getLeavesOfType("markdown");
if (leaves && leaves.length > 0) {
for (const leaf of leaves) {
const selectedFiles = leaf.view instanceof MarkdownView
? (leaf.view as MarkdownViewWithSelectedFiles).selectedFiles
: undefined;
if (selectedFiles && selectedFiles.length > 0) {
return selectedFiles[0];
}
}
}
// 方式2: 获取当前活跃文件
const activeFile = this.app.workspace.getActiveFile();
if (activeFile) {
return activeFile;
}
return null;
}
private prepareText(text: string): string {
let next = text.replace(/\r\n/g, "\n");
if (this.settings.stripFrontmatter) {
next = next.replace(/^---\n[\s\S]*?\n---\n?/, "");
}
next = normalizeFencedBlocks(next, this.settings.skipCodeBlocks);
// 过滤残留 HTML 标签
if (this.settings.filterHtmlTags) {
next = next.replace(/<[^>]+>/g, "");
}
// 过滤多余空白(空格、制表符、超过2个连续换行)
if (this.settings.filterExtraWhitespace) {
next = next.replace(/[ \t]+/g, " ");
next = next.replace(/\n{3,}/g, "\n\n");
}
// 自定义字符过滤
if (this.settings.customCharsToFilter) {
for (const character of this.settings.customCharsToFilter) {
next = next.split(character).join("");
}
}
let result = next
.replace(/!\[[^\]]*\]\([^)]+\)/g, "")
.replace(/\[[^\]]+\]\([^)]+\)/g, "")
.replace(/https?:\/\/\S+/g, "")
.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, "$2")
.replace(/\[\[([^\]]+)\]\]/g, "$1")
.replace(/^[ \t]*#{1,6}[ \t]+/gm, "")
.replace(/^[ \t]*>[ \t]?/gm, "")
.replace(/^[ \t]*[-*+][ \t]+/gm, "")
.replace(/^[ \t]*\d+\.[ \t]+/gm, "")
.replace(/\[[ xX]\][ \t]*/g, "")
.replace(/^[ \t]*[-:| ]{3,}$/gm, "")
.replace(/\|/g, " ")
.replace(/\*\*([^*]+)\*\*/g, "$1")
.replace(/\*([^*]+)\*/g, "$1")
.replace(/~~([^~]+)~~/g, "$1")
.replace(/`([^`]+)`/g, "$1")
.replace(/[\w./~ -]+:\d+(?::\d+)?/g, "")
.trim();
// 段落换行处添加停顿标记
// 将 \n\n 转换为 。\n\n(句号在换行前面,表示段落结束后的停顿)
result = result.replace(/\n\n+/g, "。\n\n");
return result;
}
private async playAudioFile(filePath: string, onPlaybackStarted?: () => void): Promise<void> {
const file = await fs.promises.readFile(filePath);
const audio = file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength);
const url = URL.createObjectURL(new Blob([audio], { type: "audio/wav" }));
this.objectUrls.push(url);
await this.playAudioUrl(url, onPlaybackStarted);
}
private playAudioUrl(url: string, onPlaybackStarted?: () => void): Promise<void> {
return new Promise((resolve, reject) => {
const audio = new Audio(url);
audio.preload = "auto";
// 应用播放速度(仅影响播放,不影响合成)
audio.playbackRate = this.settings.playbackSpeed;
this.currentAudio = audio;
audio.onended = () => {
this.currentAudio = null;
resolve();
};
audio.onerror = (e) => {
this.currentAudio = null;
reject(new Error(getAudioErrorMessage(audio)));
};
// 尝试播放
audio.play()
.then(() => {
// 播放成功,等待 onended
onPlaybackStarted?.();
this.finishCurrentPlayback = resolve;
})
.catch((error) => {
// 播放被阻止或失败,保持 audio 引用有效,等待用户点继续
this.finishCurrentPlayback = resolve;
new Notice("播放被阻止,请点击「继续」按钮播放");
console.warn("Playback blocked, waiting for user interaction", error);
// 此时 audio.paused 为 true,刷新按钮:禁用暂停、启用继续
this.refreshControllerButtons();
});
});
}
private updateStatus(state: PlaybackState, chunk?: number, total?: number) {
const prefix = "TTS";
// 从 activeFilePath 提取文件名
const fileName = this.activeFilePath ? this.activeFilePath.split("/").pop() || "" : "";
if (state === "loading") {
this.statusBarEl.setText(`${prefix}: synthesizing ${chunk}/${total}`);
this.updateController("正在合成", chunk, total, fileName);
return;
}
if (state === "playing" && chunk && total) {
this.statusBarEl.setText(`${prefix}: playing ${chunk}/${total}`);
this.updateController("正在播放", chunk, total, fileName);
return;
}
if (state === "paused") {
this.statusBarEl.setText(`${prefix}: paused`);
this.updateController("已暂停", chunk, total, fileName);
return;
}
if (state === "stopped") {
this.statusBarEl.setText(`${prefix}: stopped`);
this.updateController("已停止", chunk, total, fileName);
return;
}
this.statusBarEl.setText(`${prefix}: idle`);
this.updateController("空闲", chunk, total, fileName);
}
private createController() {
const activeDocument = this.app.workspace.containerEl.ownerDocument;
const controllerEl = activeDocument.body.createDiv({ cls: "open-reader-controller" });
this.controllerEl = controllerEl;
controllerEl.hide();
// === 顶部区域:标题 + 文件名 + 关闭按钮 ===
const header = controllerEl.createDiv({ cls: "open-reader-controller-header" });
// 拖拽手柄区域
const dragHandle = header.createDiv({ cls: "open-reader-controller-drag" });
dragHandle.setText("☰");
dragHandle.setAttribute("aria-label", "拖拽移动");
// 标题 + 文件名
const titleArea = header.createDiv({ cls: "open-reader-controller-title-area" });
this.controllerTitleEl = titleArea.createDiv({
cls: "open-reader-controller-title",
text: "Open Reader",
});
this.fileNameEl = titleArea.createDiv({
cls: "open-reader-controller-filename",
text: "",
});
// 关闭按钮
const closeButton = header.createEl("button", {
cls: "open-reader-controller-close",
attr: { "aria-label": "关闭" }
});
closeButton.setText("✕");
closeButton.addEventListener("click", () => this.hideController());
// === 进度区域 ===
const progressArea = controllerEl.createDiv({ cls: "open-reader-controller-progress" });
const progressTrack = progressArea.createDiv({ cls: "open-reader-controller-progress-track" });
this.progressBarEl = progressTrack.createDiv({ cls: "open-reader-controller-progress-fill" });
this.progressTextEl = progressArea.createDiv({ cls: "open-reader-controller-progress-text" });
// === 状态区域 ===
const statusArea = controllerEl.createDiv({ cls: "open-reader-controller-status-area" });
this.controllerStatusEl = statusArea.createDiv({
cls: "open-reader-controller-status",
text: "空闲",
});
// === 播放速度区域(仅控制 HTMLAudio.playbackRate,不影响合成)===
const speedArea = controllerEl.createDiv({ cls: "open-reader-controller-speed" });
speedArea.createDiv({ cls: "open-reader-controller-speed-label", text: "播放速度" });
const speedButtons = speedArea.createDiv({ cls: "open-reader-controller-speed-buttons" });
this.speedButtonEls = [];
for (const rate of OpenReaderPlugin.PLAYBACK_SPEED_OPTIONS) {
const btn = speedButtons.createEl("button", {
cls: "open-reader-controller-speed-btn",
text: `${rate}x`,
attr: { "data-rate": String(rate) },
});
btn.addEventListener("click", () => this.setPlaybackSpeed(rate));
this.speedButtonEls.push(btn);
}
// === 操作按钮区域 ===
const actions = controllerEl.createDiv({ cls: "open-reader-controller-actions" });
this.pauseButtonEl = actions.createEl("button", { text: "暂停" });
this.pauseButtonEl.addEventListener("click", () => this.pauseReading());
this.resumeButtonEl = actions.createEl("button", { text: "继续" });
this.resumeButtonEl.addEventListener("click", () => {
void this.resumeReading();
});
const stopButton = actions.createEl("button", { text: "停止" });
stopButton.addEventListener("click", () => this.stopReading());
// 设置按钮
const settingsButton = actions.createEl("button", { text: "⚙" });
settingsButton.setAttribute("aria-label", "设置");
settingsButton.addEventListener("click", () => {
(this.app as AppWithSettings).setting?.openTabById?.("open-reader");
});
// 目录按钮
const folderButton = actions.createEl("button", { text: "📁" });
folderButton.setAttribute("aria-label", "打开目录");
folderButton.addEventListener("click", () => {
void this.openOutputFolder();
});
// === 拖拽功能 ===
if (this.settings.enableDragToMove) {
this.setupControllerDrag();
}
// 初始化按钮状态(速度档位高亮、暂停/继续 disabled)
this.refreshControllerButtons();
}
// 设置控制器拖拽
private setupControllerDrag() {
const controllerEl = this.controllerEl;
if (!controllerEl) return;
const header = controllerEl.querySelector(".open-reader-controller-drag");
if (!header) return;
const ownerDocument = controllerEl.ownerDocument;
const ownerWindow = ownerDocument.defaultView || window;
let isDragging = false;
let startX = 0;
let startY = 0;
let startRight = 0;
let startBottom = 0;
const onMouseDown = (e: MouseEvent) => {
e.preventDefault();
isDragging = true;
startX = e.clientX;
startY = e.clientY;
// 读取当前 right/bottom 位置
const style = ownerWindow.getComputedStyle(controllerEl);
startRight = parseInt(style.right) || 24;
startBottom = parseInt(style.bottom) || 28;
// 切换到 left/top 定位以便计算
controllerEl.setCssStyles({
right: "auto",
left: `${ownerWindow.innerWidth - startRight - controllerEl.offsetWidth}px`,
top: `${ownerWindow.innerHeight - startBottom - controllerEl.offsetHeight}px`,
bottom: "auto",
});
controllerEl.classList.add("is-dragging");
};
const onMouseMove = (e: MouseEvent) => {
if (!isDragging) return;
const deltaX = e.clientX - startX;
const deltaY = e.clientY - startY;
// 新的 left/top 位置
const newLeft = Math.max(0, ownerWindow.innerWidth - startRight - controllerEl.offsetWidth + deltaX);
const newTop = Math.max(0, ownerWindow.innerHeight - startBottom - controllerEl.offsetHeight + deltaY);
controllerEl.setCssStyles({
left: `${newLeft}px`,
top: `${newTop}px`,
});
};
const onMouseUp = () => {
if (!isDragging) return;
isDragging = false;
controllerEl.classList.remove("is-dragging");
};
header.addEventListener("mousedown", onMouseDown);
ownerDocument.addEventListener("mousemove", onMouseMove);
ownerDocument.addEventListener("mouseup", onMouseUp);
}
// 隐藏控制器(停止朗读并隐藏)
private hideController() {
this.stopReading(false);
this.controllerEl?.hide();
}
private showController() {
this.controllerEl?.show();
}
private updateController(label: string, chunk?: number, total?: number, fileName?: string) {
if (!this.controllerEl || !this.controllerStatusEl) return;
// 更新状态文字
this.controllerStatusEl.setText(label);
// 更新文件名
if (this.fileNameEl) {
this.fileNameEl.setText(fileName || "");
}
// 更新进度条
if (this.progressBarEl && this.progressTextEl && chunk !== undefined && total !== undefined) {
const percent = total > 0 ? (chunk / total) * 100 : 0;
this.progressBarEl.setCssStyles({ width: `${percent}%` });
this.progressTextEl.textContent = `${chunk}/${total}`;
} else if (this.progressBarEl && this.progressTextEl) {
this.progressBarEl.setCssStyles({ width: "0%" });
this.progressTextEl.textContent = "";
}
// 更新按钮状态
this.refreshControllerButtons();
}
// 根据 currentAudio 的实际状态刷新暂停/继续按钮的 disabled 属性。
// 解决时序问题:updateStatus("playing") 调用时 currentAudio 可能尚未就绪,
// 因此在音频真正开始播放(onPlaybackStarted)或被阻止后再统一刷新。
private refreshControllerButtons() {
if (this.pauseButtonEl) {
this.pauseButtonEl.disabled = !this.currentAudio || this.currentAudio.paused;
}
if (this.resumeButtonEl) {
this.resumeButtonEl.disabled = !this.currentAudio || !this.currentAudio.paused;
}
// 同步刷新速度按钮选中态
this.refreshSpeedButtons();
}
// 切换播放速度:更新设置、作用于正在播放的音频、刷新高亮。
// 仅改变 HTMLAudio.playbackRate,不触发重新合成。
private setPlaybackSpeed(rate: number) {
this.settings.playbackSpeed = rate;
void this.saveSettings();
if (this.currentAudio) {
this.currentAudio.playbackRate = rate;
}
this.refreshSpeedButtons();
}
// 高亮当前选中的速度档位按钮
private refreshSpeedButtons() {
const current = this.settings.playbackSpeed;
for (const btn of this.speedButtonEls) {
const rate = Number(btn.getAttribute("data-rate"));
btn.toggleClass("is-active", rate === current);
}
}
private releaseObjectUrls() {
for (const url of this.objectUrls) {
URL.revokeObjectURL(url);
}
this.objectUrls = [];
}
private async ensureOutputFolder() {
const folderPath = normalizeVaultPath(this.settings.outputFolder || DEFAULT_SETTINGS.outputFolder);
await ensureVaultFolder(this.app, folderPath);
}
private getChunkOutputPath(adapter: FileSystemAdapter, chunk: number): string {
const timestamp = formatTimestamp(new Date());
const padded = String(chunk).padStart(3, "0");
return this.getNamedOutputPath(adapter, `${timestamp}-chunk-${padded}.wav`);
}
private getNamedOutputPath(adapter: FileSystemAdapter, filename: string): string {
const folderPath = normalizeVaultPath(this.settings.outputFolder || DEFAULT_SETTINGS.outputFolder);
return toNativePath(adapter.getBasePath(), `${folderPath}/${filename}`);
}
}
class OpenReaderSettingTab extends PluginSettingTab {
plugin: OpenReaderPlugin;
constructor(app: App, plugin: OpenReaderPlugin) {
super(app, plugin);
this.plugin = plugin;
}
getSettingDefinitions(): SettingDefinitionItem[] {
return [
{
type: "group",
heading: "TTS 服务 · TTS service",
items: [
{
name: "本地语音引擎 · local speech engine",
desc: "检测或安装本机 Local TTS。 · Detect or install Local TTS on this computer.",
render: (setting) => {
setting
.addButton((button) =>
button
.setButtonText(this.plugin.detectTtsctlPath() ? "重新检测 · detect" : "一键安装 · install")
.onClick(async () => {
if (!this.plugin.detectTtsctlPath()) await this.plugin.installLocalTts();
}),
)
.addButton((button) =>
button.setButtonText("项目说明 · docs").onClick(() => {
window.open("https://github.com/lornezhang66/local-tts-service#cli");
}),
);
},
},
{
name: "语速 · speech speed",
desc: "范围 0.5 到 2,推荐 0.8–1.2。 · Range: 0.5–2; recommended: 0.8–1.2.",
control: { type: "slider", key: "speed", min: 0.5, max: 2, step: 0.05 },
},
],
},
{
type: "group",
heading: "文本处理 · text processing",
items: [
{