-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
executable file
·290 lines (234 loc) · 8.74 KB
/
script.js
File metadata and controls
executable file
·290 lines (234 loc) · 8.74 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
const mp3Files = document.getElementById('mp3Files');
const tapeLengthInput = document.getElementById('tapeLength');
const trackList = document.getElementById('trackList');
const totalDurationDisplay = document.getElementById('totalDuration');
const remainingTimeDisplay = document.getElementById('remainingTime');
const recordButton = document.getElementById('recordButton');
const progress = document.getElementById('progress');
const volumeIndicator = document.createElement('div');
volumeIndicator.className = 'volume-indicator';
document.body.appendChild(volumeIndicator);
const reelImage = document.querySelector('.reel-spinner');
const STATIC_REEL = 'reel-to-reel-static.svg';
const ANIMATED_REEL = 'reel-to-reel-animated.svg';
const trackGapInput = document.getElementById('trackGap');
const body = document.body;
let totalDuration = 0;
let files = [];
let audioContext;
let analyser;
mp3Files.addEventListener('change', handleFiles);
tapeLengthInput.addEventListener('input', updateRemainingTime);
recordButton.addEventListener('click', recordToTape);
async function handleFiles(event) {
const newFiles = Array.from(event.target.files);
for (const file of newFiles) {
files.push(file);
const duration = await getDuration(file);
totalDuration += duration;
addTrackToPlaylist(file.name, duration, files.length - 1);
}
updateTotalDuration();
updateRemainingTime();
}
async function getDuration(file) {
return new Promise((resolve) => {
const audio = new Audio();
audio.preload = 'metadata';
audio.src = URL.createObjectURL(file);
audio.onloadedmetadata = () => {
resolve(audio.duration / 60); // Duration in minutes
URL.revokeObjectURL(audio.src);
};
});
}
function addTrackToPlaylist(name, duration, index) {
const li = document.createElement('li');
li.draggable = true;
li.dataset.index = index;
li.textContent = `${name} (${duration.toFixed(2)} minutes)`;
li.addEventListener('dragstart', handleDragStart);
li.addEventListener('dragover', handleDragOver);
li.addEventListener('drop', handleDrop);
li.addEventListener('dragend', handleDragEnd);
trackList.appendChild(li);
}
function updateTotalDuration() {
totalDurationDisplay.textContent = totalDuration.toFixed(2);
}
function updateRemainingTime() {
const tapeLength = parseFloat(tapeLengthInput.value);
if (tapeLength) {
const remainingTime = tapeLength - totalDuration;
remainingTimeDisplay.textContent = remainingTime.toFixed(2);
}
}
// ... other parts of the script
async function recordToTape() {
if (files.length === 0) {
alert('Please add MP3 files to the playlist.');
return;
}
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
analyser.connect(audioContext.destination);
updateVolumeIndicator();
startReelAnimation();
body.classList.add('recording-active');
console.log("Starting playback with order:");
logPlaylist();
const gapSeconds = parseFloat(trackGapInput.value) || 0;
try {
for (let i = 0; i < files.length; i++) {
console.log(`Playing track ${i}: ${files[i].name}`);
const duration = await getDuration(files[i]);
await playTrack(files[i], duration);
if (i < files.length - 1 && gapSeconds > 0) {
await addGapBetweenTracks(gapSeconds);
}
}
} catch (error) {
console.error("Playback error:", error);
}
stopReelAnimation();
body.classList.remove('recording-active');
alert('Recording completed!');
}
async function playTrack(file, duration) {
return new Promise((resolve) => {
const audio = new Audio();
audio.src = URL.createObjectURL(file);
const source = audioContext.createMediaElementSource(audio);
source.connect(analyser);
audio.currentTime = 0; // Always start from beginning
audio.play();
audio.onended = () => {
resolve();
URL.revokeObjectURL(audio.src);
};
audio.ontimeupdate = () => {
const currentPlayTime = audio.currentTime;
const progressPercent = (currentPlayTime / (totalDuration * 60)) * 100;
updateProgress(progressPercent);
const tapeLength = parseFloat(tapeLengthInput.value) * 60;
const remainingTime = tapeLength - currentPlayTime;
remainingTimeDisplay.textContent = (remainingTime / 60).toFixed(2);
};
});
}
// ... rest of the script
function updateProgress(percent) {
progress.innerHTML = `<div class="progress-bar" style="width: ${percent}%;"></div>`;
}
function updateRemainingTimeDisplay(currentTime) {
const tapeLength = parseFloat(tapeLengthInput.value) * 60;
const remainingTime = tapeLength - currentTime;
remainingTimeDisplay.textContent = (remainingTime / 60).toFixed(2);
}
function updateVolumeIndicator() {
const dataArray = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(dataArray);
const averageVolume = dataArray.reduce((a, b) => a + b) / dataArray.length;
volumeIndicator.style.height = `${averageVolume / 255 * 100}px`; // Scale height based on volume
requestAnimationFrame(updateVolumeIndicator);
}
function startReelAnimation() {
reelImage.src = ANIMATED_REEL;
}
function stopReelAnimation() {
reelImage.src = STATIC_REEL;
}
function addGapBetweenTracks(seconds) {
return new Promise(resolve => {
console.log(`Adding ${seconds} second gap`);
const startTime = audioContext.currentTime;
function checkGap() {
const elapsed = audioContext.currentTime - startTime;
if (elapsed >= seconds) {
resolve();
} else {
requestAnimationFrame(checkGap);
}
}
checkGap();
});
}
let draggedItem = null;
function handleDragStart(e) {
draggedItem = e.target;
e.target.style.opacity = '0.4';
}
function handleDragOver(e) {
e.preventDefault();
const targetItem = e.target;
// Only handle drag over list items
if (targetItem.tagName === 'LI') {
const bounding = targetItem.getBoundingClientRect();
const offset = bounding.y + (bounding.height/2);
if (e.clientY - offset > 0) {
targetItem.style.borderBottom = 'solid 2px #eed49f';
targetItem.style.borderTop = '';
} else {
targetItem.style.borderTop = 'solid 2px #eed49f';
targetItem.style.borderBottom = '';
}
}
}
function handleDrop(e) {
e.preventDefault();
const targetItem = e.target;
// Only handle drops on list items
if (targetItem.tagName === 'LI' && draggedItem !== targetItem) {
// Get the current order of all items
const items = Array.from(trackList.children);
const oldIndex = items.indexOf(draggedItem);
// Remove and insert the dragged item
draggedItem.parentNode.removeChild(draggedItem);
// Determine if dropping before or after the target
const bounding = targetItem.getBoundingClientRect();
const insertAfter = e.clientY > (bounding.top + bounding.height / 2);
if (insertAfter) {
targetItem.parentNode.insertBefore(draggedItem, targetItem.nextSibling);
} else {
targetItem.parentNode.insertBefore(draggedItem, targetItem);
}
// Get the new order of items
const newItems = Array.from(trackList.children);
const newIndex = newItems.indexOf(draggedItem);
// Reorder the files array to match
const [movedFile] = files.splice(oldIndex, 1);
files.splice(newIndex, 0, movedFile);
// Update all indices
newItems.forEach((item, index) => {
item.dataset.index = index;
});
// Log the new order for debugging
logPlaylist();
}
clearDragOverStyles();
}
function handleDragEnd(e) {
e.target.style.opacity = '';
clearDragOverStyles();
}
function clearDragOverStyles() {
const items = trackList.querySelectorAll('li');
items.forEach(item => {
item.style.borderTop = '';
item.style.borderBottom = '';
});
}
function updatePlaylistIndices() {
const items = trackList.querySelectorAll('li');
items.forEach((item, index) => {
item.dataset.index = index;
});
}
// Add this function to help with debugging
function logPlaylist() {
console.log("Current playlist order:");
files.forEach((file, index) => {
console.log(`${index}: ${file.name}`);
});
}