-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
279 lines (233 loc) · 9.71 KB
/
Copy pathscript.js
File metadata and controls
279 lines (233 loc) · 9.71 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
document.addEventListener('DOMContentLoaded', () => {
// DOM Elements
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const cameraSelect = document.getElementById('cameraSelect');
const startButton = document.getElementById('startButton');
const captureButton = document.getElementById('captureButton');
const recordButton = document.getElementById('recordButton');
const stopButton = document.getElementById('stopButton');
const galleryItems = document.getElementById('galleryItems');
// State
let stream = null;
let mediaRecorder = null;
let recordedChunks = [];
let isRecording = false;
// Get available cameras
async function getCameras() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter(device => device.kind === 'videoinput');
cameraSelect.innerHTML = '<option value="">Select Camera</option>';
videoDevices.forEach(device => {
const option = document.createElement('option');
option.value = device.deviceId;
option.text = device.label || `Camera ${cameraSelect.length + 1}`;
cameraSelect.appendChild(option);
});
return videoDevices;
} catch (err) {
console.error('Error getting cameras:', err);
alert('Error accessing cameras. Please make sure you have granted camera permissions.');
return [];
}
}
// Start camera with selected device
async function startCamera(deviceId) {
// Stop any existing stream
if (stream) {
stream.getTracks().forEach(track => track.stop());
}
const constraints = {
video: {
deviceId: deviceId ? { exact: deviceId } : undefined,
width: { ideal: 1280 },
height: { ideal: 720 },
facingMode: deviceId ? undefined : 'environment'
},
audio: false
};
try {
stream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = stream;
// Enable buttons
captureButton.disabled = false;
recordButton.disabled = false;
// If we didn't specify a device, update the dropdown to show the active camera
if (!deviceId) {
const videoTrack = stream.getVideoTracks()[0];
const settings = videoTrack.getSettings();
if (settings.deviceId) {
cameraSelect.value = settings.deviceId;
}
}
return true;
} catch (err) {
console.error('Error accessing camera:', err);
alert('Could not access the camera. Please make sure you have granted camera permissions.');
return false;
}
}
// Take a photo
function takePhoto() {
if (!stream) return;
const context = canvas.getContext('2d');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
context.drawImage(video, 0, 0, canvas.width, canvas.height);
// Create a data URL for the image
const imageDataUrl = canvas.toDataURL('image/png');
// Add to gallery
addToGallery(imageDataUrl, 'image');
// Optional: Download the image
// downloadImage(imageDataUrl);
}
// Start video recording
function startRecording() {
if (!stream) return;
recordedChunks = [];
// Try to use mp4 format for better compatibility
const options = {
mimeType: 'video/webm;codecs=vp9,opus',
videoBitsPerSecond: 2500000 // 2.5Mbps
};
// Fallback to default if the preferred mimeType is not supported
if (!MediaRecorder.isTypeSupported(options.mimeType)) {
console.log('Preferred mimeType not supported, using default');
options.mimeType = ''; // Let the browser choose the best option
}
try {
mediaRecorder = new MediaRecorder(stream, options);
console.log('Using mimeType:', mediaRecorder.mimeType);
} catch (e) {
console.error('Exception while creating MediaRecorder:', e);
alert('Error initializing video recording. Please try a different browser or camera.');
return;
}
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start(100); // Collect 100ms of data
isRecording = true;
// Update UI
recordButton.disabled = true;
stopButton.disabled = false;
}
// Stop video recording
function stopRecording() {
if (!mediaRecorder || !isRecording) return;
mediaRecorder.stop();
isRecording = false;
// Update UI
recordButton.disabled = false;
stopButton.disabled = true;
}
// Handle recorded data
function handleDataAvailable(event) {
if (event.data.size > 0) {
recordedChunks.push(event.data);
// If recording has stopped, process the recorded data
if (!isRecording) {
const blob = new Blob(recordedChunks, { type: 'video/mp4; codecs=avc1.42E01E' });
const videoUrl = URL.createObjectURL(blob);
// Create a download link for better browser compatibility
const a = document.createElement('a');
a.href = videoUrl;
a.download = `recording-${new Date().toISOString().slice(0, 19).replace(/[:.]/g, '-')}.mp4`;
// Add to gallery with the video element and download link
addToGallery(videoUrl, 'video', a.download);
}
}
}
// Add media to gallery
function addToGallery(url, type, filename = '') {
const item = document.createElement('div');
item.className = 'gallery-item';
const mediaContainer = document.createElement('div');
mediaContainer.className = 'media-container';
const mediaElement = type === 'image'
? document.createElement('img')
: document.createElement('video');
mediaElement.src = url;
if (type === 'video') {
mediaElement.controls = true;
mediaElement.controlsList = 'nodownload'; // Hide download button to encourage right-click save
mediaElement.style.width = '100%';
mediaElement.style.height = 'auto';
// Add context menu for better video handling
mediaElement.oncontextmenu = (e) => {
// Allow the default context menu for better browser handling
return true;
};
// Add a download button for better UX
const downloadBtn = document.createElement('button');
downloadBtn.className = 'download-btn';
downloadBtn.title = 'Download Video';
downloadBtn.innerHTML = '↓';
downloadBtn.onclick = (e) => {
e.stopPropagation();
const a = document.createElement('a');
a.href = url;
a.download = filename || `video-${Date.now()}.mp4`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
mediaContainer.appendChild(downloadBtn);
}
mediaContainer.appendChild(mediaElement);
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.title = 'Delete';
deleteBtn.innerHTML = '×';
deleteBtn.onclick = (e) => {
e.stopPropagation();
item.remove();
// Revoke the object URL to free up memory
if (type === 'video') {
URL.revokeObjectURL(url);
}
};
item.appendChild(mediaContainer);
item.appendChild(deleteBtn);
// Add to the beginning of the gallery
galleryItems.insertBefore(item, galleryItems.firstChild);
}
// Download image (optional)
function downloadImage(dataUrl) {
const link = document.createElement('a');
link.download = `photo-${new Date().toISOString().slice(0, 10)}.png`;
link.href = dataUrl;
link.click();
}
// Event Listeners
startButton.addEventListener('click', () => {
const deviceId = cameraSelect.value;
if (deviceId) {
startCamera(deviceId);
} else {
alert('Please select a camera first');
}
});
cameraSelect.addEventListener('change', () => {
// Auto-start camera when a device is selected
const deviceId = cameraSelect.value;
if (deviceId) {
startCamera(deviceId);
}
});
captureButton.addEventListener('click', takePhoto);
recordButton.addEventListener('click', startRecording);
stopButton.addEventListener('click', stopRecording);
// Initialize
getCameras().then(devices => {
if (devices.length > 0) {
// Auto-start the first camera
startCamera(devices[0].deviceId);
}
});
// Clean up on page unload
window.addEventListener('beforeunload', () => {
if (stream) {
stream.getTracks().forEach(track => track.stop());
}
});
});