-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer.js
More file actions
589 lines (495 loc) · 17.4 KB
/
renderer.js
File metadata and controls
589 lines (495 loc) · 17.4 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
// DOM元素
const recordBtn = document.getElementById("recordBtn");
const pauseBtn = document.getElementById("pauseBtn");
const stopBtn = document.getElementById("stopBtn");
const saveBtn = document.getElementById("saveBtn");
const timerElement = document.getElementById("timer");
const statusElement = document.getElementById("status");
const recordAudioCheckbox = document.getElementById("recordAudio");
const maxDurationInput = document.getElementById("maxDuration");
const loadingOverlay = document.getElementById("loadingOverlay");
const videoPreviewContainer = document.getElementById("videoPreviewContainer");
const videoPreview = document.getElementById("videoPreview");
let selectedSource = null;
// 录制状态变量
let mediaRecorder;
let recordedChunks = [];
let stream;
let startTime;
let pausedTime = 0;
let totalPausedTime = 0;
let lastPauseTime = 0;
let isPaused = false;
let timerInterval;
let maxDurationMs = 0; // 最大录制时长(毫秒)
let maxDurationTimer = null; // 最大录制时长定时器
// 初始化
document.addEventListener("DOMContentLoaded", () => {
// 检查API是否可用
console.log("API可用性检查:", !!window.electronAPI);
if (window.electronAPI) {
console.log("可用的API:", Object.keys(window.electronAPI));
}
// 初始化按钮状态
recordBtn.style.display = "inline-block"; // 显示开始录制按钮
pauseBtn.style.display = "none"; // 隐藏暂停录制按钮
stopBtn.style.display = "none"; // 隐藏停止录制按钮
saveBtn.style.display = "none"; // 隐藏保存录制按钮
recordBtn.addEventListener("click", startRecording);
pauseBtn.addEventListener("click", togglePauseRecording);
stopBtn.addEventListener("click", stopRecording);
saveBtn.addEventListener("click", saveRecording);
// 设置保存响应处理
window.electronAPI.onSaveComplete(handleSaveResponse);
});
// 启动录制
async function startRecording() {
try {
// 隐藏视频预览
videoPreviewContainer.style.display = "none";
// 获取最大录制时长设置(分钟)
const maxDurationMinutes = parseInt(maxDurationInput.value, 10) || 0;
maxDurationMs = maxDurationMinutes * 60 * 1000; // 转换为毫秒
// 清除之前的最大时长定时器(如果有)
if (maxDurationTimer) {
clearTimeout(maxDurationTimer);
maxDurationTimer = null;
}
statusElement.textContent = "正在获取屏幕源...";
// 获取可用的屏幕源
const sources = await window.electronAPI.captureScreen();
if (!sources || sources.length === 0) {
throw new Error("找不到可用的屏幕源");
}
// 只有一个屏幕时自动选择,多个屏幕时显示前端对话框
recordBtn.style.display = "none"; // 隐藏开始录制按钮
if (sources.length === 1) {
statusElement.textContent = "检测到单个屏幕,自动选择...";
selectedSource = sources[0];
} else {
statusElement.textContent = "请选择要录制的屏幕";
selectedSource = await showScreenSelectionDialog(sources);
if (!selectedSource) {
statusElement.textContent = "已取消屏幕选择";
recordBtn.style.display = "inline-block"; // 重新显示开始录制按钮
return;
}
}
statusElement.textContent = "准备开始录制...";
await showCountdown(3);
// 设置媒体约束
const constraints = {
audio: recordAudioCheckbox.checked
? {
mandatory: {
chromeMediaSource: "desktop",
},
}
: false,
video: {
mandatory: {
chromeMediaSource: "desktop",
chromeMediaSourceId: selectedSource.id,
},
},
};
console.log("使用的媒体约束:", JSON.stringify(constraints));
// 获取媒体流
stream = await navigator.mediaDevices.getUserMedia(constraints);
// 创建MediaRecorder实例
mediaRecorder = new MediaRecorder(stream, {
mimeType: "video/webm; codecs=vp9",
});
// 收集录制的数据
mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) {
recordedChunks.push(e.data);
}
};
// 录制结束处理
mediaRecorder.onstop = () => {
stopTimer();
statusElement.textContent = `录制已完成。${
recordAudioCheckbox.checked ? "包含系统声音。" : ""
}可以保存录制内容。`;
};
// 开始录制
mediaRecorder.start(100);
startTimer();
// 设置最大录制时长定时器(如果设置了最大时长)
if (maxDurationMs > 0) {
maxDurationTimer = setTimeout(() => {
if (mediaRecorder && mediaRecorder.state !== "inactive") {
// 显示应用窗口
window.electronAPI.showWindow();
// 停止录制
stopRecording();
// 提示用户已达到最大录制时长
statusElement.textContent = `已达到最大录制时长 ${maxDurationMinutes} 分钟,录制已自动停止。`;
}
}, maxDurationMs);
}
// 更新UI状态
recordBtn.style.display = "none"; // 隐藏开始录制按钮
pauseBtn.style.display = "inline-block"; // 显示暂停录制按钮
stopBtn.style.display = "inline-block"; // 显示停止录制按钮
saveBtn.style.display = "none"; // 隐藏保存录制按钮
recordAudioCheckbox.disabled = true;
maxDurationInput.disabled = true; // 录制中禁用最大时长设置
recordBtn.classList.add("recording");
recordBtn.textContent = "正在录制";
pauseBtn.textContent = "暂停录制";
pauseBtn.classList.remove("paused");
isPaused = false;
totalPausedTime = 0;
// 更新状态信息,包括最大录制时长
let statusText = `正在录制屏幕${
recordAudioCheckbox.checked ? "和系统声音" : ""
}`;
if (maxDurationMs > 0) {
statusText += `,最大录制时长: ${maxDurationMinutes} 分钟`;
}
statusElement.textContent = statusText + "...";
// 最小化窗口并开始录制
window.electronAPI.minimizeWindow();
} catch (error) {
console.error("启动录制时出错:", error);
statusElement.textContent = `录制失败: ${error.message}`;
recordBtn.style.display = "inline-block"; // 重新显示开始录制按钮
pauseBtn.style.display = "none"; // 隐藏暂停录制按钮
stopBtn.style.display = "none"; // 隐藏停止录制按钮
saveBtn.style.display = "none"; // 隐藏保存录制按钮
recordAudioCheckbox.disabled = false;
maxDurationInput.disabled = false;
}
}
// 暂停/继续录制
function togglePauseRecording() {
if (!mediaRecorder || mediaRecorder.state === "inactive") {
return;
}
if (isPaused) {
// 继续录制
resumeRecording();
} else {
// 暂停录制
pauseRecording();
}
}
// 暂停录制
function pauseRecording() {
if (!mediaRecorder || mediaRecorder.state !== "recording") {
return;
}
// 暂停 MediaRecorder
mediaRecorder.pause();
// 记录暂停时间
lastPauseTime = Date.now();
// 暂停计时器
stopTimer();
// 如果设置了最大录制时长,暂停定时器
if (maxDurationTimer) {
clearTimeout(maxDurationTimer);
// 计算剩余时间
const elapsedTime = Date.now() - startTime - totalPausedTime;
const remainingTime = Math.max(0, maxDurationMs - elapsedTime);
// 保存剩余时间
maxDurationMs = remainingTime;
}
// 更新UI状态
pauseBtn.textContent = "继续录制";
pauseBtn.classList.add("paused");
statusElement.textContent = "录制已暂停";
isPaused = true;
}
// 继续录制
function resumeRecording() {
if (!mediaRecorder || mediaRecorder.state !== "paused") {
return;
}
// 继续 MediaRecorder
mediaRecorder.resume();
// 计算暂停时间
const currentTime = Date.now();
const pauseDuration = currentTime - lastPauseTime;
totalPausedTime += pauseDuration;
// 继续计时器
startTimer();
// 如果设置了最大录制时长,重新设置定时器
if (maxDurationMs > 0) {
maxDurationTimer = setTimeout(() => {
if (mediaRecorder && mediaRecorder.state !== "inactive") {
// 显示应用窗口
window.electronAPI.showWindow();
// 停止录制
stopRecording();
// 提示用户已达到最大录制时长
const maxDurationMinutes = Math.ceil(maxDurationMs / (60 * 1000));
statusElement.textContent = `已达到最大录制时长 ${maxDurationMinutes} 分钟,录制已自动停止。`;
}
}, maxDurationMs);
}
// 更新UI状态
pauseBtn.textContent = "暂停录制";
pauseBtn.classList.remove("paused");
// 更新状态信息,包括最大录制时长
let statusText = `继续录制屏幕${
recordAudioCheckbox.checked ? "和系统声音" : ""
}`;
if (maxDurationMs > 0) {
const maxDurationMinutes = Math.ceil(maxDurationMs / (60 * 1000));
statusText += `,剩余时间: 约 ${maxDurationMinutes} 分钟`;
}
statusElement.textContent = statusText + "...";
isPaused = false;
}
// 停止录制
function stopRecording() {
if (!mediaRecorder || mediaRecorder.state === "inactive") {
return;
}
// 清除最大录制时长定时器
if (maxDurationTimer) {
clearTimeout(maxDurationTimer);
maxDurationTimer = null;
}
mediaRecorder.stop();
stream.getTracks().forEach((track) => track.stop());
// 更新UI状态
recordBtn.style.display = "inline-block"; // 显示开始录制按钮
pauseBtn.style.display = "none"; // 隐藏暂停录制按钮
stopBtn.style.display = "none"; // 隐藏停止录制按钮
saveBtn.style.display = "inline-block"; // 显示保存录制按钮
recordAudioCheckbox.disabled = false;
maxDurationInput.disabled = false; // 重新启用最大时长设置
recordBtn.classList.remove("recording");
pauseBtn.classList.remove("paused");
recordBtn.textContent = "开始录制";
pauseBtn.textContent = "暂停录制";
isPaused = false;
// 创建并显示视频预览
createVideoPreview();
}
// 创建视频预览
function createVideoPreview() {
if (!recordedChunks.length) {
return;
}
// 创建视频Blob
const blob = new Blob(recordedChunks, { type: "video/webm" });
// 创建视频URL
const videoURL = URL.createObjectURL(blob);
// 设置视频源
videoPreview.src = videoURL;
// 显示视频预览容器
videoPreviewContainer.style.display = "block";
// 视频加载完成后自动播放
videoPreview.onloadedmetadata = () => {
videoPreview.play();
};
}
// 保存录制
function saveRecording() {
if (!recordedChunks.length) {
statusElement.textContent = "没有录制内容可保存";
return;
}
// 显示格式选择弹窗
showFormatSelectionDialog();
}
// 显示格式选择对话框
function showFormatSelectionDialog() {
// 创建弹窗元素
const modal = document.createElement("div");
modal.className = "modal";
modal.style.display = "flex";
modal.style.zIndex = "3000";
const modalContent = document.createElement("div");
modalContent.className = "modal-content";
modalContent.style.maxWidth = "400px";
const title = document.createElement("div");
title.className = "modal-title";
title.textContent = "请选择保存格式";
title.style.marginBottom = "20px";
const buttonsContainer = document.createElement("div");
buttonsContainer.style.display = "flex";
buttonsContainer.style.justifyContent = "space-around";
buttonsContainer.style.marginTop = "20px";
// WebM按钮
const webmButton = document.createElement("button");
webmButton.textContent = "保存为WebM格式";
webmButton.style.backgroundColor = "#3498db";
webmButton.style.marginRight = "10px";
// MP4按钮
const mp4Button = document.createElement("button");
mp4Button.textContent = "保存为MP4格式";
mp4Button.style.backgroundColor = "#2ecc71";
// 添加按钮点击事件
webmButton.addEventListener("click", () => {
modal.style.display = "none";
document.body.removeChild(modal);
processAndSaveRecording("webm");
});
mp4Button.addEventListener("click", () => {
modal.style.display = "none";
document.body.removeChild(modal);
processAndSaveRecording("mp4");
});
// 组装弹窗
buttonsContainer.appendChild(webmButton);
buttonsContainer.appendChild(mp4Button);
modalContent.appendChild(title);
modalContent.appendChild(buttonsContainer);
modal.appendChild(modalContent);
// 添加到页面
document.body.appendChild(modal);
}
// 处理并保存录制内容
function processAndSaveRecording(format) {
statusElement.textContent = "正在处理录制内容,请稍候...";
loadingOverlay.style.display = "flex";
// 隐藏视频预览
videoPreviewContainer.style.display = "none";
// 合并所有录制的片段
const blob = new Blob(recordedChunks, { type: "video/webm" });
// 将Blob转换为Buffer
const reader = new FileReader();
reader.onload = () => {
const buffer = new Uint8Array(reader.result);
// 通过IPC发送到主进程保存,并指定格式
window.electronAPI.saveFile(buffer, format);
statusElement.textContent = `正在保存为${format.toUpperCase()}格式...`;
};
reader.readAsArrayBuffer(blob);
}
// 处理保存录制文件的响应
function handleSaveResponse(response) {
loadingOverlay.style.display = "none";
if (response.success) {
statusElement.textContent = `${response.message}:${response.filePath}`;
// 清除录制的数据
recordedChunks = [];
saveBtn.style.display = "none"; // 隐藏保存录制按钮
// 清除视频预览
videoPreview.src = "";
videoPreviewContainer.style.display = "none";
// 释放视频URL资源
if (videoPreview.src) {
URL.revokeObjectURL(videoPreview.src);
}
} else {
statusElement.textContent = response.message;
}
}
// 计时器功能
function startTimer() {
if (!isPaused) {
// 如果是第一次开始录制
startTime = Date.now();
}
updateTimer();
timerInterval = setInterval(updateTimer, 1000);
}
function stopTimer() {
clearInterval(timerInterval);
}
function updateTimer() {
// 计算实际录制时间,减去暂停的时间
const currentTime = Date.now();
const elapsedTime = currentTime - startTime - totalPausedTime;
const seconds = Math.floor((elapsedTime / 1000) % 60);
const minutes = Math.floor((elapsedTime / (1000 * 60)) % 60);
const hours = Math.floor(elapsedTime / (1000 * 60 * 60));
timerElement.textContent = `${padZero(hours)}:${padZero(minutes)}:${padZero(
seconds
)}`;
}
function padZero(num) {
return num.toString().padStart(2, "0");
}
// 显示屏幕选择对话框
function showScreenSelectionDialog(sources) {
return new Promise((resolve) => {
const modal = document.getElementById("screenModal");
const screenList = document.getElementById("screenList");
const confirmBtn = document.getElementById("confirmScreenSelect");
const cancelBtn = document.getElementById("cancelScreenSelect");
// 清空并重新填充屏幕列表
screenList.innerHTML = "";
let selectedSource = null;
sources.forEach((source) => {
const item = document.createElement("div");
item.className = "screen-item";
item.innerHTML = `
<div class="screen-thumbnail" style="background-color: #f0f0f0; display: flex; align-items: center; justify-content: center;">
<div style="position: absolute; font-size: 14px; color: #666;">${source.displaySize}</div>
</div>
<div class="screen-name">${source.name}</div>
`;
item.addEventListener("click", () => {
// 更新选中状态
document.querySelectorAll(".screen-item").forEach((el) => {
el.classList.remove("selected");
});
item.classList.add("selected");
selectedSource = source;
confirmBtn.style.display = "inline-block"; // 显示确认按钮
});
screenList.appendChild(item);
});
// 确认按钮点击处理
confirmBtn.addEventListener(
"click",
() => {
modal.style.display = "none";
resolve(selectedSource);
},
{ once: true }
);
// 取消按钮点击处理
cancelBtn.addEventListener(
"click",
() => {
modal.style.display = "none";
resolve(null);
},
{ once: true }
);
// 显示对话框
modal.style.display = "flex";
confirmBtn.style.display = "none"; // 初始隐藏确认按钮,直到选择了屏幕
});
}
// 显示倒计时动画
async function showCountdown(seconds) {
return new Promise((resolve) => {
const countdownOverlay = document.createElement("div");
countdownOverlay.style.position = "fixed";
countdownOverlay.style.top = "0";
countdownOverlay.style.left = "0";
countdownOverlay.style.width = "100%";
countdownOverlay.style.height = "100%";
countdownOverlay.style.backgroundColor = "rgba(0,0,0,0.7)";
countdownOverlay.style.display = "flex";
countdownOverlay.style.justifyContent = "center";
countdownOverlay.style.alignItems = "center";
countdownOverlay.style.zIndex = "2000";
countdownOverlay.style.fontSize = "120px";
countdownOverlay.style.color = "white";
countdownOverlay.style.fontWeight = "bold";
countdownOverlay.style.textShadow = "0 0 20px #3498db";
document.body.appendChild(countdownOverlay);
let count = seconds;
countdownOverlay.textContent = count;
const timer = setInterval(() => {
count--;
if (count <= 0) {
clearInterval(timer);
document.body.removeChild(countdownOverlay);
resolve();
} else {
countdownOverlay.textContent = count;
}
}, 1000);
});
}