SignorNessuno commited on
Commit
dd5133c
·
verified ·
1 Parent(s): dd69801

Add 2 files

Browse files
Files changed (2) hide show
  1. README.md +7 -5
  2. index.html +1227 -19
README.md CHANGED
@@ -1,10 +1,12 @@
1
  ---
2
- title: Loopstation
3
- emoji: 😻
4
- colorFrom: pink
5
- colorTo: indigo
6
  sdk: static
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: loopstation
3
+ emoji: 🐳
4
+ colorFrom: red
5
+ colorTo: gray
6
  sdk: static
7
  pinned: false
8
+ tags:
9
+ - deepsite
10
  ---
11
 
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
index.html CHANGED
@@ -1,19 +1,1227 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Advanced Audio Looper</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
+ <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
10
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.js"></script>
11
+ <script src="https://cdn.jsdelivr.net/npm/recordrtc@5.6.2/RecordRTC.min.js"></script>
12
+ <style>
13
+ :root {
14
+ --background-color: #1a1a1a;
15
+ --grid-background: #2a2a2a;
16
+ --cell-color: #444;
17
+ /* Percussion Colors */
18
+ --cell-active-kick: #ff6b6b; /* Red */
19
+ --cell-active-snare: #ffa07a; /* Light Salmon */
20
+ --cell-active-clap: #ffd700; /* Gold */
21
+ --cell-active-hihat: #98fb98; /* Pale Green */
22
+ --cell-active-tom: #ff8c00; /* Dark Orange */
23
+ --cell-active-crash: #00bfff; /* Deep Sky Blue */
24
+ --cell-active-ride: #9370db; /* Medium Purple */
25
+ --cell-active-perc: #ff69b4; /* Hot Pink */
26
+ /* Note Color */
27
+ --cell-active-note: #4ecdc4; /* Teal */
28
+ --cell-highlight: #666;
29
+ --text-color: #e0e0e0;
30
+ --control-background: #333;
31
+ --button-color: #555;
32
+ --button-hover: #666;
33
+ --button-active: #4ecdc4; /* Teal for general active state */
34
+ --button-drum-active: #ff8c00; /* Dark Orange for active drum tool */
35
+ --button-demo-color: #8a2be2; /* Blue Violet for Demo button */
36
+ --button-demo-hover: #9932cc; /* Dark Orchid */
37
+ --button-record-color: #ff4444; /* Red for Record button */
38
+ --button-record-active: #cc0000; /* Darker red when recording */
39
+ --font-family: 'Roboto', sans-serif;
40
+
41
+ /* Default grid cell size */
42
+ --cell-size: 40px;
43
+ --grid-gap: 5px;
44
+ }
45
+
46
+ /* Basic Reset and Box Sizing */
47
+ * {
48
+ box-sizing: border-box;
49
+ margin: 0;
50
+ padding: 0;
51
+ }
52
+
53
+ html, body {
54
+ height: 100%; /* Ensure body takes full height */
55
+ }
56
+
57
+ body {
58
+ font-family: var(--font-family);
59
+ background-color: var(--background-color);
60
+ color: var(--text-color);
61
+ display: flex;
62
+ flex-direction: column;
63
+ justify-content: center;
64
+ align-items: center;
65
+ padding: 10px; /* Add padding for smaller screens */
66
+ /* Allow scrolling if content overflows */
67
+ overflow-y: auto;
68
+ min-height: 100vh;
69
+ /* Improve touch behavior on iOS */
70
+ -webkit-tap-highlight-color: transparent;
71
+ }
72
+
73
+ .looper-container {
74
+ display: flex;
75
+ flex-direction: column;
76
+ justify-content: center;
77
+ align-items: center;
78
+ gap: 20px;
79
+ padding: 20px;
80
+ background-color: var(--grid-background);
81
+ border-radius: 10px;
82
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
83
+ width: 100%; /* Take full width available */
84
+ max-width: 1000px; /* Increased max width */
85
+ }
86
+
87
+ .grid-section {
88
+ display: flex;
89
+ flex-direction: column;
90
+ align-items: center;
91
+ gap: 15px;
92
+ width: 100%;
93
+ }
94
+
95
+ .grid-container {
96
+ width: 100%;
97
+ overflow-x: auto;
98
+ padding-bottom: 10px;
99
+ }
100
+
101
+ .grid {
102
+ display: grid;
103
+ /* Calculate grid size based on variables */
104
+ grid-template-columns: repeat(var(--num-cols, 8), var(--cell-size));
105
+ grid-template-rows: repeat(var(--num-rows, 8), var(--cell-size));
106
+ gap: var(--grid-gap);
107
+ background-color: var(--grid-background);
108
+ padding: 10px;
109
+ border-radius: 8px;
110
+ border: 1px solid var(--cell-color);
111
+ width: fit-content; /* Fit the content size */
112
+ min-width: 100%;
113
+ margin: 0 auto;
114
+ }
115
+
116
+ .cell {
117
+ background-color: var(--cell-color);
118
+ border-radius: 4px;
119
+ cursor: pointer;
120
+ transition: background-color 0.1s ease-in-out, transform 0.1s ease, box-shadow 0.1s ease;
121
+ box-shadow: inset 0 1px 2px rgba(0,0,0,0.3);
122
+ position: relative;
123
+ /* Ensure cells maintain aspect ratio */
124
+ width: var(--cell-size);
125
+ height: var(--cell-size);
126
+ }
127
+
128
+ .cell:hover {
129
+ filter: brightness(1.2);
130
+ }
131
+
132
+ /* Active Cell Styling */
133
+ .cell.active {
134
+ filter: brightness(1.1);
135
+ }
136
+ .cell.active.kick { background-color: var(--cell-active-kick); box-shadow: 0 0 8px var(--cell-active-kick); }
137
+ .cell.active.snare { background-color: var(--cell-active-snare); box-shadow: 0 0 8px var(--cell-active-snare); }
138
+ .cell.active.clap { background-color: var(--cell-active-clap); box-shadow: 0 0 8px var(--cell-active-clap); }
139
+ .cell.active.hihat { background-color: var(--cell-active-hihat); box-shadow: 0 0 8px var(--cell-active-hihat); }
140
+ .cell.active.tom { background-color: var(--cell-active-tom); box-shadow: 0 0 8px var(--cell-active-tom); }
141
+ .cell.active.crash { background-color: var(--cell-active-crash); box-shadow: 0 0 8px var(--cell-active-crash); }
142
+ .cell.active.ride { background-color: var(--cell-active-ride); box-shadow: 0 0 8px var(--cell-active-ride); }
143
+ .cell.active.perc { background-color: var(--cell-active-perc); box-shadow: 0 0 8px var(--cell-active-perc); }
144
+ .cell.active.note { background-color: var(--cell-active-note); box-shadow: 0 0 8px var(--cell-active-note); }
145
+
146
+
147
+ .cell.highlight {
148
+ /* Use outline instead of scale to prevent layout shifts */
149
+ outline: 2px solid var(--cell-highlight);
150
+ outline-offset: -2px;
151
+ background-color: var(--cell-highlight) !important; /* Ensure highlight overrides */
152
+ /* transform: scale(1.05); */ /* Removed scale to avoid minor layout shifts */
153
+ box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.3);
154
+ }
155
+
156
+ /* Controls Styling */
157
+ .controls-row {
158
+ display: flex;
159
+ flex-direction: row;
160
+ gap: 15px;
161
+ width: 100%;
162
+ flex-wrap: wrap;
163
+ justify-content: center;
164
+ }
165
+
166
+ .control-group {
167
+ background-color: var(--control-background);
168
+ padding: 15px;
169
+ border-radius: 8px;
170
+ display: flex;
171
+ flex-direction: column;
172
+ gap: 10px;
173
+ min-width: 150px;
174
+ }
175
+
176
+ .control-group label,
177
+ .control-group span {
178
+ font-size: 14px;
179
+ display: block;
180
+ margin-bottom: 3px;
181
+ text-align: center;
182
+ }
183
+ .control-group span.value-display {
184
+ font-weight: bold;
185
+ min-height: 1.2em; /* Prevent layout jump when value appears */
186
+ }
187
+
188
+
189
+ .control-group input[type="range"] {
190
+ width: 100%;
191
+ cursor: pointer;
192
+ }
193
+
194
+ .control-group select {
195
+ width: 100%;
196
+ padding: 8px; /* Slightly more padding */
197
+ border-radius: 4px;
198
+ background-color: var(--cell-color);
199
+ color: var(--text-color);
200
+ border: 1px solid var(--button-color);
201
+ font-family: var(--font-family);
202
+ font-size: 14px;
203
+ }
204
+
205
+ .playback-controls, .drum-selector {
206
+ display: flex;
207
+ gap: 10px;
208
+ align-items: center;
209
+ justify-content: center;
210
+ background-color: var(--control-background);
211
+ padding: 10px 15px;
212
+ border-radius: 8px;
213
+ flex-wrap: wrap; /* Allow buttons to wrap */
214
+ width: 100%; /* Take full width within grid-section */
215
+ }
216
+
217
+ .playback-controls label {
218
+ margin-right: 5px;
219
+ flex-shrink: 0; /* Prevent label from shrinking */
220
+ }
221
+ .playback-controls .tempo-value {
222
+ min-width: 35px;
223
+ text-align: right;
224
+ font-weight: bold;
225
+ flex-shrink: 0;
226
+ }
227
+ .playback-controls input[type="range"] {
228
+ flex-grow: 1; /* Allow slider to take available space */
229
+ min-width: 80px; /* Minimum width for the slider */
230
+ }
231
+
232
+
233
+ /* Button Styling */
234
+ button {
235
+ padding: 8px 12px; /* Adjust padding */
236
+ font-size: 14px;
237
+ font-weight: bold;
238
+ font-family: var(--font-family);
239
+ background-color: var(--button-color);
240
+ color: var(--text-color);
241
+ border: none;
242
+ border-radius: 5px;
243
+ cursor: pointer;
244
+ transition: background-color 0.2s ease, box-shadow 0.2s ease;
245
+ box-shadow: 0 2px 4px rgba(0,0,0,0.2);
246
+ flex-shrink: 0; /* Prevent buttons shrinking too much */
247
+ }
248
+ button:hover {
249
+ background-color: var(--button-hover);
250
+ }
251
+ #play-stop-button.active {
252
+ background-color: var(--button-active);
253
+ color: var(--background-color);
254
+ }
255
+ .drum-selector button.active {
256
+ background-color: var(--button-drum-active);
257
+ box-shadow: 0 0 8px var(--button-drum-active);
258
+ }
259
+ /* Demo Button Style */
260
+ #demo-button {
261
+ background-color: var(--button-demo-color);
262
+ }
263
+ #demo-button:hover {
264
+ background-color: var(--button-demo-hover);
265
+ }
266
+ /* Record Button Style */
267
+ #record-button {
268
+ background-color: var(--button-record-color);
269
+ }
270
+ #record-button:hover {
271
+ background-color: var(--button-record-active);
272
+ }
273
+ #record-button.recording {
274
+ background-color: var(--button-record-active);
275
+ animation: pulse 1.5s infinite;
276
+ }
277
+ @keyframes pulse {
278
+ 0% { opacity: 1; }
279
+ 50% { opacity: 0.7; }
280
+ 100% { opacity: 1; }
281
+ }
282
+
283
+ /* Vertical Volume Slider */
284
+ .volume-control {
285
+ display: flex;
286
+ /* Default to vertical */
287
+ flex-direction: column;
288
+ align-items: center;
289
+ gap: 5px;
290
+ }
291
+ .volume-control input[type="range"] {
292
+ /* Vertical styles */
293
+ writing-mode: bt-lr; /* IE/Edge */
294
+ -webkit-appearance: slider-vertical; /* WebKit */
295
+ width: 8px;
296
+ height: 120px;
297
+ padding: 0 5px;
298
+ background: var(--cell-color);
299
+ border-radius: 5px;
300
+ cursor: pointer;
301
+ }
302
+ .volume-control input[type="range"]::-webkit-slider-thumb {
303
+ -webkit-appearance: none; appearance: none; width: 18px; height: 18px; background: var(--button-hover); border-radius: 50%; cursor: pointer;
304
+ }
305
+ .volume-control input[type="range"]::-moz-range-thumb {
306
+ width: 18px; height: 18px; background: var(--button-hover); border-radius: 50%; cursor: pointer; border: none;
307
+ }
308
+
309
+ /* Grid Size Controls */
310
+ .grid-size-controls {
311
+ display: flex;
312
+ flex-direction: column;
313
+ gap: 10px;
314
+ }
315
+ .grid-size-row {
316
+ display: flex;
317
+ justify-content: space-between;
318
+ align-items: center;
319
+ }
320
+ .grid-size-controls button {
321
+ padding: 6px 10px;
322
+ font-size: 12px;
323
+ min-width: 30px;
324
+ }
325
+
326
+ /* Message Box Styling */
327
+ #message-box {
328
+ position: fixed;
329
+ top: 10px; /* Closer to top */
330
+ left: 50%;
331
+ transform: translateX(-50%);
332
+ background-color: var(--button-active);
333
+ color: var(--background-color);
334
+ padding: 8px 15px; /* Adjusted padding */
335
+ border-radius: 5px;
336
+ box-shadow: 0 2px 5px rgba(0,0,0,0.3);
337
+ z-index: 1000;
338
+ display: none;
339
+ font-weight: bold;
340
+ font-size: 14px;
341
+ text-align: center;
342
+ max-width: 90%; /* Prevent it being too wide */
343
+ }
344
+
345
+ /* --- Responsive Styles --- */
346
+
347
+ /* Medium Screens (Tablets) */
348
+ @media (max-width: 768px) {
349
+ body {
350
+ align-items: flex-start; /* Align to top for scroll */
351
+ padding: 15px;
352
+ }
353
+ .looper-container {
354
+ flex-direction: column; /* Stack sections vertically */
355
+ align-items: center; /* Center items in the column */
356
+ gap: 25px;
357
+ padding: 15px;
358
+ }
359
+ .grid-section {
360
+ width: 100%; /* Allow grid section to take full width */
361
+ max-width: 450px; /* Limit max width */
362
+ }
363
+ .controls-row {
364
+ width: 100%; /* Controls take full width */
365
+ max-width: 450px; /* Limit max width */
366
+ flex-direction: row; /* Arrange controls horizontally */
367
+ flex-wrap: wrap; /* Allow control groups to wrap */
368
+ justify-content: center; /* Center control groups */
369
+ }
370
+ .control-group {
371
+ flex-grow: 1; /* Allow groups to grow */
372
+ min-width: 150px; /* Minimum width for control groups */
373
+ }
374
+ .volume-control {
375
+ height: auto; /* Reset height */
376
+ }
377
+ }
378
+
379
+ /* Small Screens (Phones) */
380
+ @media (max-width: 480px) {
381
+ :root {
382
+ /* Smaller cells for phones */
383
+ --cell-size: 30px;
384
+ --grid-gap: 3px;
385
+ }
386
+ body {
387
+ padding: 5px; /* Reduce body padding */
388
+ }
389
+ .looper-container {
390
+ padding: 10px;
391
+ gap: 15px;
392
+ }
393
+ .grid {
394
+ padding: 5px; /* Reduce grid padding */
395
+ }
396
+ .controls-row {
397
+ flex-direction: column; /* Stack control groups vertically again */
398
+ align-items: center; /* Center groups */
399
+ width: 100%;
400
+ max-width: 300px; /* Further limit width */
401
+ }
402
+ .control-group {
403
+ width: 100%; /* Make control groups full width */
404
+ min-width: unset; /* Remove min-width */
405
+ }
406
+ .playback-controls, .drum-selector {
407
+ padding: 8px 10px;
408
+ gap: 8px;
409
+ }
410
+ button {
411
+ padding: 6px 10px;
412
+ font-size: 13px;
413
+ }
414
+ .control-group label, .control-group span {
415
+ font-size: 13px;
416
+ }
417
+ .volume-control {
418
+ /* Make volume horizontal on small screens */
419
+ flex-direction: row;
420
+ width: 100%;
421
+ justify-content: center;
422
+ align-items: center; /* Center label/value vertically */
423
+ }
424
+ .volume-control input[type="range"] {
425
+ /* Reset vertical styles */
426
+ -webkit-appearance: none;
427
+ appearance: none;
428
+ writing-mode: horizontal-tb;
429
+ /* Apply horizontal styles */
430
+ width: 60%; /* Adjust width as needed */
431
+ height: 8px;
432
+ max-width: 150px;
433
+ padding: 0; /* Remove vertical padding */
434
+ }
435
+ .volume-control input[type="range"]::-webkit-slider-thumb {
436
+ /* Ensure thumb styles are appropriate for horizontal */
437
+ width: 16px; /* Slightly smaller thumb */
438
+ height: 16px;
439
+ }
440
+ .volume-control input[type="range"]::-moz-range-thumb {
441
+ width: 16px;
442
+ height: 16px;
443
+ }
444
+ #message-box {
445
+ top: 5px;
446
+ font-size: 12px;
447
+ padding: 6px 10px;
448
+ }
449
+ }
450
+ /* Very Small Screens */
451
+ @media (max-width: 360px) {
452
+ :root {
453
+ --cell-size: 28px; /* Even smaller cells */
454
+ --grid-gap: 2px;
455
+ }
456
+ button {
457
+ padding: 5px 8px;
458
+ font-size: 12px;
459
+ }
460
+ .playback-controls, .drum-selector {
461
+ gap: 5px;
462
+ }
463
+ }
464
+
465
+ </style>
466
+ </head>
467
+ <body>
468
+ <div id="message-box">Click 'Play' or grid to start audio</div>
469
+
470
+ <div class="looper-container">
471
+
472
+ <div class="grid-section">
473
+ <div class="grid-container">
474
+ <div class="grid" id="grid-container"></div>
475
+ </div>
476
+
477
+ <div class="drum-selector" id="drum-selector">
478
+ <span>Drum Tool:</span>
479
+ <button data-sound="kick">Kick</button>
480
+ <button data-sound="snare">Snare</button>
481
+ <button data-sound="clap">Clap</button>
482
+ <button data-sound="hihat">HiHat</button>
483
+ <button data-sound="tom">Tom</button>
484
+ <button data-sound="crash">Crash</button>
485
+ <button data-sound="ride">Ride</button>
486
+ <button data-sound="perc">Perc</button>
487
+ </div>
488
+
489
+ <div class="playback-controls">
490
+ <button id="play-stop-button">Play</button>
491
+ <button id="demo-button">Demo</button>
492
+ <button id="record-button">Record</button>
493
+ <label for="tempo">Tempo:</label>
494
+ <input type="range" id="tempo" name="tempo" min="40" max="240" value="120">
495
+ <span class="tempo-value" id="tempo-value">120</span> BPM
496
+ </div>
497
+
498
+ <div class="controls-row">
499
+ <div class="control-group volume-control">
500
+ <label for="volume">Volume</label>
501
+ <input type="range" id="volume" name="volume" min="-40" max="0" value="-6" step="1">
502
+ <span class="value-display" id="volume-value">-6 dB</span>
503
+ </div>
504
+
505
+ <div class="control-group">
506
+ <label for="synth-type">Note Synth</label>
507
+ <select id="synth-type" name="synth-type">
508
+ <option value="MembraneSynth">Membrane</option>
509
+ <option value="Synth">Synth</option>
510
+ <option value="AMSynth">AM</option>
511
+ <option value="FMSynth">FM</option>
512
+ <option value="MonoSynth">MonoSynth</option>
513
+ </select>
514
+
515
+ <label for="decay">Decay/Release</label>
516
+ <input type="range" id="decay" name="decay" min="0.01" max="1.5" value="0.2" step="0.01">
517
+ <span class="value-display" id="decay-value">0.20 s</span>
518
+
519
+ <label for="reverb">Reverb Wet</label>
520
+ <input type="range" id="reverb" name="reverb" min="0" max="1" value="0.1" step="0.05">
521
+ <span class="value-display" id="reverb-value">0.10</span>
522
+ </div>
523
+
524
+ <div class="control-group grid-size-controls">
525
+ <div class="grid-size-row">
526
+ <span>Columns:</span>
527
+ <div>
528
+ <button id="decrease-cols">-</button>
529
+ <span id="cols-value">8</span>
530
+ <button id="increase-cols">+</button>
531
+ </div>
532
+ </div>
533
+ <div class="grid-size-row">
534
+ <span>Rows:</span>
535
+ <div>
536
+ <button id="decrease-rows">-</button>
537
+ <span id="rows-value">8</span>
538
+ <button id="increase-rows">+</button>
539
+ </div>
540
+ </div>
541
+ </div>
542
+ </div>
543
+ </div>
544
+ </div>
545
+
546
+ <script>
547
+ // --- DOM Elements ---
548
+ const gridContainer = document.getElementById('grid-container');
549
+ const playStopButton = document.getElementById('play-stop-button');
550
+ const demoButton = document.getElementById('demo-button');
551
+ const recordButton = document.getElementById('record-button');
552
+ const tempoSlider = document.getElementById('tempo');
553
+ const tempoValueDisplay = document.getElementById('tempo-value');
554
+ const volumeSlider = document.getElementById('volume');
555
+ const volumeValueDisplay = document.getElementById('volume-value');
556
+ const messageBox = document.getElementById('message-box');
557
+ const synthTypeSelector = document.getElementById('synth-type');
558
+ const decaySlider = document.getElementById('decay');
559
+ const decayValueDisplay = document.getElementById('decay-value');
560
+ const reverbSlider = document.getElementById('reverb');
561
+ const reverbValueDisplay = document.getElementById('reverb-value');
562
+ const drumSelectorContainer = document.getElementById('drum-selector');
563
+ const drumButtons = drumSelectorContainer.querySelectorAll('button');
564
+ const decreaseColsBtn = document.getElementById('decrease-cols');
565
+ const increaseColsBtn = document.getElementById('increase-cols');
566
+ const colsValueDisplay = document.getElementById('cols-value');
567
+ const decreaseRowsBtn = document.getElementById('decrease-rows');
568
+ const increaseRowsBtn = document.getElementById('increase-rows');
569
+ const rowsValueDisplay = document.getElementById('rows-value');
570
+
571
+ // --- Constants ---
572
+ const MIN_COLS = 4;
573
+ const MAX_COLS = Infinity; // Removed column limit
574
+ const MIN_ROWS = 4;
575
+ const MAX_ROWS = 16;
576
+ const NOTES = ["C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5", "D5", "E5", "F5", "G5", "A5", "B5"];
577
+ const DRUM_SOUNDS = ['kick', 'snare', 'clap', 'hihat', 'tom', 'crash', 'ride', 'perc'];
578
+
579
+ // --- State ---
580
+ let numCols = 8;
581
+ let numRows = 8;
582
+ let gridState = Array(numRows).fill(null).map((_, r) =>
583
+ Array(numCols).fill(r === 0 ? null : false)
584
+ );
585
+ let synths = [];
586
+ let percussion = {};
587
+ let reverbEffect;
588
+ let masterVolume;
589
+ let sequence;
590
+ let currentColumn = 0;
591
+ let isPlaying = false;
592
+ let audioInitialized = false;
593
+ let audioContextStarted = false;
594
+ let currentSynthType = 'MembraneSynth';
595
+ let currentDecay = 0.2;
596
+ let selectedDrumSound = DRUM_SOUNDS[0];
597
+ let currentDemoIndex = -1;
598
+ let recorder;
599
+ let isRecording = false;
600
+ let audioStream;
601
+
602
+ // --- Demo Patterns ---
603
+ const demoPatterns = [
604
+ [['kick', null, 'snare', null, 'kick', null, 'snare', null],[true, false, false, false, true, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false]],
605
+ [['kick', 'hihat', 'kick', 'hihat', 'kick', 'hihat', 'kick', 'hihat'],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[true, false, false, true, false, false, true, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false]],
606
+ [['kick', 'hihat', 'snare', 'hihat', 'kick', 'hihat', 'snare', 'hihat'],[true, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[true, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[true, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false]],
607
+ [['kick', null, null, 'clap', 'kick', 'kick', null, 'clap'],[true, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, true, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, true, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, true, false]],
608
+ [['kick', 'hihat', 'snare', 'hihat', 'kick', 'hihat', 'snare', 'hihat'],[true, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, true, false, false, false],[false, false, false, false, false, false, false, false],[false, false, false, false, false, false, false, false]]
609
+ ];
610
+
611
+ // --- Tone.js Setup ---
612
+
613
+ function setupNoteSynths() {
614
+ console.log("Setting up note synths...");
615
+ synths.forEach(synth => synth?.dispose());
616
+ synths = [];
617
+ const synthOptions = {
618
+ envelope: { attack: 0.005, decay: 0.1, sustain: 0.3, release: currentDecay },
619
+ ...(currentSynthType === 'MonoSynth' && { volume: -8 }),
620
+ ...(currentSynthType === 'FMSynth' && { harmonicity: 3, modulationIndex: 10 }),
621
+ ...(currentSynthType === 'AMSynth' && { harmonicity: 3 }),
622
+ ...(currentSynthType === 'MembraneSynth' && { pitchDecay: 0.01, octaves: 4 })
623
+ };
624
+ for (let i = 0; i < numRows - 1; i++) {
625
+ if (Tone[currentSynthType]) {
626
+ const synth = new Tone[currentSynthType](synthOptions);
627
+ // Always connect to reverbEffect, which connects to masterVolume
628
+ if (reverbEffect) synth.connect(reverbEffect);
629
+ else console.error("Reverb effect not ready for synth connection");
630
+ synths.push(synth);
631
+ } else {
632
+ console.error(`Invalid synth type: ${currentSynthType}`);
633
+ synths.push(null);
634
+ }
635
+ }
636
+ console.log(`Created ${synths.length} synths of type ${currentSynthType}.`);
637
+ }
638
+
639
+ /**
640
+ * Initializes the full audio setup (synths, effects, sequence) AFTER Tone.start() is successful.
641
+ */
642
+ async function completeAudioSetup() {
643
+ if (audioInitialized) return; // Prevent running setup twice
644
+ console.log("Completing audio setup...");
645
+ try {
646
+ // Create master volume control and connect to destination (speakers)
647
+ masterVolume = new Tone.Volume(parseFloat(volumeSlider.value)).toDestination();
648
+ console.log("Master volume created.");
649
+
650
+ // Create reverb effect and connect it to the master volume
651
+ reverbEffect = new Tone.Reverb({
652
+ wet: parseFloat(reverbSlider.value), // Initial wetness from slider
653
+ decay: 1.5 // Fixed decay time for the reverb
654
+ }).connect(masterVolume);
655
+ // Wait for the reverb impulse response to load
656
+ await reverbEffect.ready;
657
+ console.log("Reverb effect ready.");
658
+
659
+ // Create percussion synth instances and connect them to the reverb
660
+ percussion = {
661
+ kick: new Tone.MembraneSynth({ pitchDecay: 0.05, octaves: 10, oscillator: { type: "sine" }, envelope: { attack: 0.001, decay: 0.4, sustain: 0.01, release: 0.8, attackCurve: "exponential" } }).connect(reverbEffect),
662
+ snare: new Tone.NoiseSynth({ noise: { type: 'white' }, envelope: { attack: 0.005, decay: 0.15, sustain: 0, release: 0.1 } }).connect(reverbEffect),
663
+ clap: new Tone.NoiseSynth({ noise: { type: 'pink' }, envelope: { attack: 0.001, decay: 0.1, sustain: 0, release: 0.15, attackCurve: 'exponential' } }).connect(reverbEffect),
664
+ hihat: new Tone.MetalSynth({ frequency: 300, envelope: { attack: 0.001, decay: 0.05, release: 0.05 }, harmonicity: 5.1, modulationIndex: 32, resonance: 4000, octaves: 1.5 }).connect(reverbEffect),
665
+ tom: new Tone.MembraneSynth({ pitchDecay: 0.1, octaves: 8, oscillator: { type: "sine" }, envelope: { attack: 0.001, decay: 0.5, sustain: 0.01, release: 0.5 } }).connect(reverbEffect),
666
+ crash: new Tone.MetalSynth({ frequency: 400, envelope: { attack: 0.001, decay: 0.5, release: 0.5 }, harmonicity: 8, modulationIndex: 40, resonance: 3000 }).connect(reverbEffect),
667
+ ride: new Tone.MetalSynth({ frequency: 500, envelope: { attack: 0.001, decay: 0.3, release: 0.3 }, harmonicity: 5, modulationIndex: 20, resonance: 2000 }).connect(reverbEffect),
668
+ perc: new Tone.NoiseSynth({ noise: { type: 'white' }, envelope: { attack: 0.001, decay: 0.2, sustain: 0, release: 0.2 } }).connect(reverbEffect)
669
+ };
670
+ console.log("Percussion synths created.");
671
+
672
+ // Get initial synth settings from controls
673
+ currentSynthType = synthTypeSelector.value;
674
+ currentDecay = parseFloat(decaySlider.value);
675
+ // Create the note synths based on initial settings
676
+ setupNoteSynths();
677
+
678
+ // Create the sequence (will be updated when grid size changes)
679
+ createSequence();
680
+
681
+ // Set the initial tempo from the slider
682
+ Tone.Transport.bpm.value = parseInt(tempoSlider.value);
683
+ audioInitialized = true; // Mark full setup as complete
684
+ hideMessage(); // Hide any initialization messages
685
+ setActiveDrumButton(selectedDrumSound); // Highlight the default drum button
686
+ console.log("Audio setup fully complete.");
687
+
688
+ } catch (err) {
689
+ console.error("Error during completeAudioSetup:", err);
690
+ showMessage("Failed to set up audio components.", true);
691
+ audioInitialized = false; // Ensure flag is false on failure
692
+ }
693
+ }
694
+
695
+ function createSequence() {
696
+ // Dispose of the old sequence if it exists
697
+ if (sequence) {
698
+ sequence.dispose();
699
+ }
700
+
701
+ // Define the steps for the sequence (0 to numCols - 1)
702
+ const steps = Array.from(Array(numCols).keys());
703
+
704
+ // Create the main Tone.js Sequence
705
+ sequence = new Tone.Sequence((time, col) => {
706
+ currentColumn = col; // Update the current column index
707
+
708
+ // Schedule visual highlighting using Tone.Draw for accurate timing
709
+ Tone.Draw.schedule(() => {
710
+ highlightColumn(col);
711
+ }, time);
712
+
713
+ // Iterate through each row for the current column (step)
714
+ for (let row = 0; row < numRows; row++) {
715
+ const cellState = gridState[row][col]; // Get state (sound name or boolean)
716
+
717
+ if (cellState) { // If the cell is active
718
+ if (row === 0) { // Percussion Row
719
+ const soundName = cellState;
720
+ if (percussion[soundName]?.triggerAttackRelease) {
721
+ try {
722
+ if (soundName === 'snare' || soundName === 'clap' || soundName === 'perc') {
723
+ percussion[soundName].triggerAttackRelease("8n", time);
724
+ } else if (soundName === 'hihat' || soundName === 'crash' || soundName === 'ride') {
725
+ percussion[soundName].triggerAttackRelease("C1", "16n", time);
726
+ } else {
727
+ percussion[soundName].triggerAttackRelease("C1", "8n", time);
728
+ }
729
+ } catch (e) { console.error(`Error triggering percussion ${soundName} at col ${col}:`, e); }
730
+ }
731
+ } else { // Note Rows (1 to numRows-1)
732
+ const synthIndex = row - 1;
733
+ if (synths[synthIndex]?.triggerAttackRelease) {
734
+ try {
735
+ const note = NOTES[synthIndex % NOTES.length];
736
+ synths[synthIndex].triggerAttackRelease(note, "8n", time);
737
+ } catch (e) { console.error(`Error triggering synth ${synthIndex} (${currentSynthType}) at col ${col}:`, e); }
738
+ }
739
+ }
740
+ }
741
+ }
742
+ }, steps, "8n"); // Sequence runs at "8n" (eighth note) interval
743
+ console.log("Sequence created with", numCols, "steps");
744
+ }
745
+
746
+ /**
747
+ * Attempts to start the Tone.js AudioContext. Must be called from a user gesture.
748
+ */
749
+ async function startAudioContext() {
750
+ if (audioContextStarted) return true; // Already started
751
+
752
+ console.log("Attempting to start Tone.js Audio Context...");
753
+ try {
754
+ await Tone.start();
755
+ // Check context state after starting
756
+ if (Tone.context.state === 'running') {
757
+ audioContextStarted = true;
758
+ console.log("Tone.js Audio Context started successfully. State:", Tone.context.state);
759
+ // Now complete the rest of the setup
760
+ await completeAudioSetup();
761
+ return true;
762
+ } else {
763
+ console.warn("Tone.start() completed but context state is:", Tone.context.state);
764
+ showMessage("Audio context did not start properly.", true);
765
+ return false;
766
+ }
767
+ } catch (err) {
768
+ console.error("Tone.start() failed:", err);
769
+ showMessage("Could not start audio. User interaction might be required.", true);
770
+ audioContextStarted = false;
771
+ return false;
772
+ }
773
+ }
774
+
775
+ // --- Recording Functions ---
776
+ async function startRecording() {
777
+ if (!audioInitialized) {
778
+ showMessage("Please initialize audio first by clicking Play or a grid cell");
779
+ return;
780
+ }
781
+
782
+ try {
783
+ // Get the audio stream from the Web Audio destination
784
+ const dest = Tone.context.createMediaStreamDestination();
785
+ Tone.Destination.connect(dest);
786
+
787
+ // Create a recorder
788
+ recorder = new RecordRTC(dest.stream, {
789
+ type: 'audio',
790
+ mimeType: 'audio/wav',
791
+ recorderType: RecordRTC.StereoAudioRecorder,
792
+ desiredSampRate: 44100,
793
+ numberOfAudioChannels: 2
794
+ });
795
+
796
+ // Start recording
797
+ recorder.startRecording();
798
+ isRecording = true;
799
+ recordButton.classList.add('recording');
800
+ showMessage("Recording started...");
801
+ console.log("Recording started");
802
+ } catch (err) {
803
+ console.error("Recording error:", err);
804
+ showMessage("Recording failed to start", true);
805
+ isRecording = false;
806
+ recordButton.classList.remove('recording');
807
+ }
808
+ }
809
+
810
+ async function stopRecording() {
811
+ if (!isRecording || !recorder) return;
812
+
813
+ return new Promise((resolve) => {
814
+ recorder.stopRecording(() => {
815
+ isRecording = false;
816
+ recordButton.classList.remove('recording');
817
+
818
+ // Get the recorded blob
819
+ const blob = recorder.getBlob();
820
+
821
+ // Create download link
822
+ const url = URL.createObjectURL(blob);
823
+ const a = document.createElement('a');
824
+ a.style.display = 'none';
825
+ a.href = url;
826
+ a.download = `looper-recording-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')}.wav`;
827
+ document.body.appendChild(a);
828
+ a.click();
829
+
830
+ // Clean up
831
+ setTimeout(() => {
832
+ document.body.removeChild(a);
833
+ window.URL.revokeObjectURL(url);
834
+ }, 100);
835
+
836
+ showMessage("Recording saved as WAV file");
837
+ console.log("Recording stopped and saved");
838
+
839
+ // Dispose the recorder
840
+ recorder.destroy();
841
+ recorder = null;
842
+ resolve();
843
+ });
844
+ });
845
+ }
846
+
847
+ async function toggleRecording() {
848
+ if (isRecording) {
849
+ await stopRecording();
850
+ } else {
851
+ await startRecording();
852
+ }
853
+ }
854
+
855
+ // --- Grid Creation & Update ---
856
+
857
+ function createGrid() {
858
+ gridContainer.innerHTML = '';
859
+ // Update CSS variables for grid size
860
+ gridContainer.style.setProperty('--num-cols', numCols);
861
+ gridContainer.style.setProperty('--num-rows', numRows);
862
+
863
+ for (let row = 0; row < numRows; row++) {
864
+ for (let col = 0; col < numCols; col++) {
865
+ const cell = document.createElement('div');
866
+ cell.classList.add('cell');
867
+ cell.dataset.row = row;
868
+ cell.dataset.col = col;
869
+ cell.dataset.type = (row === 0) ? 'percussion' : 'note';
870
+ // Use touchstart primarily for mobile, click as fallback
871
+ cell.addEventListener('touchstart', handleCellInteraction, { passive: true });
872
+ cell.addEventListener('click', handleCellInteraction);
873
+ gridContainer.appendChild(cell);
874
+ }
875
+ }
876
+ updateGridVisuals();
877
+ }
878
+
879
+ function updateGridVisuals() {
880
+ for (let row = 0; row < numRows; row++) {
881
+ for (let col = 0; col < numCols; col++) {
882
+ const cell = gridContainer.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`);
883
+ if (!cell) continue;
884
+ const cellState = gridState[row][col];
885
+ const isActive = !!cellState;
886
+ cell.classList.remove('active', 'note', ...DRUM_SOUNDS);
887
+ if (isActive) {
888
+ cell.classList.add('active');
889
+ if (row === 0) {
890
+ if (typeof cellState === 'string') cell.classList.add(cellState);
891
+ } else {
892
+ cell.classList.add('note');
893
+ }
894
+ }
895
+ }
896
+ }
897
+ }
898
+
899
+ function resizeGrid(newCols, newRows) {
900
+ // Create a new grid state with the new dimensions
901
+ const newGridState = Array(newRows).fill(null).map((_, row) =>
902
+ Array(newCols).fill(null).map((_, col) => {
903
+ // If we're within the bounds of the old grid, copy the value
904
+ if (row < numRows && col < numCols) {
905
+ return gridState[row][col];
906
+ }
907
+ // For new rows/columns, set default values
908
+ return row === 0 ? null : false;
909
+ })
910
+ );
911
+
912
+ // Update the grid dimensions
913
+ numCols = newCols;
914
+ numCols = Math.max(MIN_COLS, numCols); // Removed upper limit
915
+ numRows = newRows;
916
+ numRows = Math.max(MIN_ROWS, Math.min(MAX_ROWS, numRows));
917
+
918
+ // Update the display
919
+ colsValueDisplay.textContent = numCols;
920
+ rowsValueDisplay.textContent = numRows;
921
+
922
+ // Update the grid state
923
+ gridState = newGridState;
924
+
925
+ // Recreate the grid UI
926
+ createGrid();
927
+
928
+ // If audio is initialized, recreate the sequence
929
+ if (audioInitialized) {
930
+ createSequence();
931
+ if (isPlaying) {
932
+ Tone.Transport.stop();
933
+ sequence.start(0);
934
+ Tone.Transport.start();
935
+ }
936
+ }
937
+ }
938
+
939
+ // --- Event Handlers ---
940
+
941
+ /**
942
+ * Unified handler for cell clicks and touches.
943
+ */
944
+ async function handleCellInteraction(event) {
945
+ // Ensure audio context is started on the first interaction
946
+ if (!audioContextStarted) {
947
+ showMessage("Initializing Audio...");
948
+ const success = await startAudioContext();
949
+ if (!success) return; // Stop if context didn't start
950
+ }
951
+
952
+ // If full setup isn't complete yet, wait or show message
953
+ if (!audioInitialized) {
954
+ showMessage("Audio setup in progress...");
955
+ console.log("Cell interaction ignored: audio not fully initialized yet.");
956
+ return;
957
+ }
958
+
959
+ // Proceed with cell logic only if audio is fully ready
960
+ const cell = event.currentTarget;
961
+ const row = parseInt(cell.dataset.row);
962
+ const col = parseInt(cell.dataset.col);
963
+
964
+ if (row === 0) { // Percussion Row
965
+ const currentSoundInCell = gridState[row][col];
966
+ if (currentSoundInCell === selectedDrumSound) {
967
+ gridState[row][col] = null;
968
+ cell.classList.remove('active', selectedDrumSound);
969
+ } else {
970
+ if (currentSoundInCell) cell.classList.remove(currentSoundInCell);
971
+ gridState[row][col] = selectedDrumSound;
972
+ cell.classList.add('active', selectedDrumSound);
973
+ }
974
+ } else { // Note Rows
975
+ gridState[row][col] = !gridState[row][col];
976
+ cell.classList.toggle('active', gridState[row][col]);
977
+ cell.classList.toggle('note', gridState[row][col]);
978
+ }
979
+ }
980
+
981
+ /**
982
+ * Handles clicks/touches on the Play/Stop button.
983
+ */
984
+ async function handlePlayStopInteraction() {
985
+ // Ensure audio context is started first
986
+ if (!audioContextStarted) {
987
+ showMessage("Initializing Audio...");
988
+ const success = await startAudioContext();
989
+ if (!success) return; // Stop if context didn't start
990
+ }
991
+
992
+ // Wait until full setup is complete before toggling playback
993
+ if (!audioInitialized) {
994
+ showMessage("Audio setup in progress...");
995
+ console.log("Play/Stop ignored: audio not fully initialized yet.");
996
+ return;
997
+ }
998
+
999
+ // If audio is ready, toggle playback
1000
+ togglePlayback();
1001
+ }
1002
+
1003
+ function togglePlayback() {
1004
+ if (!audioInitialized || !sequence) {
1005
+ console.warn("Toggle playback called before sequence is ready.");
1006
+ return;
1007
+ }
1008
+
1009
+ // Check AudioContext state before trying to play
1010
+ if (Tone.context.state === 'suspended') {
1011
+ console.log("Audio context is suspended, attempting to resume...");
1012
+ Tone.context.resume().then(() => {
1013
+ console.log("Context resumed.");
1014
+ // Try toggling again after resume
1015
+ togglePlaybackInternal();
1016
+ }).catch(err => {
1017
+ console.error("Failed to resume audio context:", err);
1018
+ showMessage("Could not resume audio.", true);
1019
+ });
1020
+ } else if (Tone.context.state === 'running') {
1021
+ togglePlaybackInternal();
1022
+ } else {
1023
+ console.error("Cannot toggle playback, Tone.context state is:", Tone.context.state);
1024
+ showMessage("Audio context issue. State: " + Tone.context.state, true);
1025
+ }
1026
+ }
1027
+
1028
+ /** Internal playback toggle logic, called when context is running */
1029
+ function togglePlaybackInternal() {
1030
+ if (isPlaying) {
1031
+ console.log("Stopping transport...");
1032
+ Tone.Transport.stop();
1033
+ sequence.stop();
1034
+ playStopButton.textContent = 'Play';
1035
+ playStopButton.classList.remove('active');
1036
+ clearHighlight();
1037
+ isPlaying = false;
1038
+ } else {
1039
+ console.log("Starting transport...");
1040
+ Tone.Transport.start();
1041
+ sequence.start(0);
1042
+ playStopButton.textContent = 'Stop';
1043
+ playStopButton.classList.add('active');
1044
+ isPlaying = true;
1045
+ }
1046
+ }
1047
+
1048
+ /** Handles clicks/touches on the Demo button. */
1049
+ async function handleDemoInteraction() {
1050
+ // Ensure audio context is started first
1051
+ if (!audioContextStarted) {
1052
+ showMessage("Please click Play/Grid first to initialize audio.");
1053
+ const success = await startAudioContext(); // Optionally try to init here too
1054
+ if (!success) return;
1055
+ }
1056
+ if (!audioInitialized) {
1057
+ showMessage("Audio setup in progress...");
1058
+ return;
1059
+ }
1060
+
1061
+ currentDemoIndex = (currentDemoIndex + 1) % demoPatterns.length;
1062
+ const patternToLoad = demoPatterns[currentDemoIndex];
1063
+
1064
+ // Resize grid to match demo pattern if needed
1065
+ const demoCols = patternToLoad[0].length;
1066
+ const demoRows = patternToLoad.length;
1067
+
1068
+ if (demoCols !== numCols || demoRows !== numRows) {
1069
+ resizeGrid(demoCols, demoRows);
1070
+ }
1071
+
1072
+ // Copy the pattern to our grid state
1073
+ gridState = patternToLoad.map(row => [...row]);
1074
+ updateGridVisuals();
1075
+ showMessage(`Loaded Demo Pattern ${currentDemoIndex + 1}`);
1076
+ console.log(`Loaded Demo Pattern ${currentDemoIndex + 1}`);
1077
+ }
1078
+
1079
+ function handleTempoChange(event) {
1080
+ const newTempo = parseInt(event.target.value);
1081
+ tempoValueDisplay.textContent = newTempo;
1082
+ if (audioInitialized) Tone.Transport.bpm.value = newTempo;
1083
+ }
1084
+
1085
+ function handleVolumeChange(event) {
1086
+ const newVolume = parseFloat(event.target.value);
1087
+ volumeValueDisplay.textContent = `${newVolume} dB`;
1088
+ if (audioInitialized && masterVolume) {
1089
+ // Clamp the volume to prevent distortion
1090
+ const clampedVolume = Math.max(-40, Math.min(0, newVolume));
1091
+ masterVolume.volume.value = clampedVolume;
1092
+ // Update the display with the clamped value
1093
+ volumeValueDisplay.textContent = `${clampedVolume} dB`;
1094
+ }
1095
+ }
1096
+
1097
+ function handleSynthTypeChange(event) {
1098
+ currentSynthType = event.target.value;
1099
+ console.log("Synth type changed to:", currentSynthType);
1100
+ if (audioInitialized) {
1101
+ const wasPlaying = isPlaying;
1102
+ if (wasPlaying) togglePlayback(); // Stop playback before changing synths
1103
+ console.log("Setting up new synths due to type change...");
1104
+ setupNoteSynths(); // Recreate synths
1105
+ // No need to resume playback automatically, user can press play again
1106
+ } else {
1107
+ console.log("Synth type changed, but audio not initialized yet. Will apply on init.");
1108
+ }
1109
+ }
1110
+
1111
+ function handleDecayChange(event) {
1112
+ currentDecay = parseFloat(event.target.value);
1113
+ decayValueDisplay.textContent = `${currentDecay.toFixed(2)} s`;
1114
+ if (audioInitialized) {
1115
+ synths.forEach(synth => {
1116
+ if (synth?.envelope) {
1117
+ if (typeof synth.envelope.release !== 'undefined') synth.envelope.release = currentDecay;
1118
+ if (synth.filterEnvelope && typeof synth.filterEnvelope.release !== 'undefined') synth.filterEnvelope.release = currentDecay * 1.5;
1119
+ }
1120
+ });
1121
+ }
1122
+ }
1123
+
1124
+ function handleReverbChange(event) {
1125
+ const newWetness = parseFloat(event.target.value);
1126
+ reverbValueDisplay.textContent = newWetness.toFixed(2);
1127
+ if (audioInitialized && reverbEffect) reverbEffect.wet.value = newWetness;
1128
+ }
1129
+
1130
+ function handleDrumToolSelect(event) {
1131
+ const button = event.target.closest('button');
1132
+ if (button?.dataset.sound) {
1133
+ selectedDrumSound = button.dataset.sound;
1134
+ setActiveDrumButton(selectedDrumSound);
1135
+ console.log("Selected drum tool:", selectedDrumSound);
1136
+ }
1137
+ }
1138
+
1139
+ function setActiveDrumButton(soundName) {
1140
+ drumButtons.forEach(btn => btn.classList.toggle('active', btn.dataset.sound === soundName));
1141
+ }
1142
+
1143
+ function handleGridSizeChange(colsDelta, rowsDelta) {
1144
+ const newCols = Math.max(MIN_COLS, numCols + colsDelta); // Removed upper limit
1145
+ const newRows = Math.max(MIN_ROWS, Math.min(MAX_ROWS, numRows + rowsDelta));
1146
+
1147
+ if (newCols !== numCols || newRows !== numRows) {
1148
+ resizeGrid(newCols, newRows);
1149
+ }
1150
+ }
1151
+
1152
+ // --- Visual Updates During Playback ---
1153
+
1154
+ function highlightColumn(colIndex) {
1155
+ clearHighlight();
1156
+ const cells = gridContainer.querySelectorAll(`.cell[data-col="${colIndex}"]`);
1157
+ cells.forEach(cell => cell.classList.add('highlight'));
1158
+ }
1159
+
1160
+ function clearHighlight() {
1161
+ const highlightedCells = gridContainer.querySelectorAll('.cell.highlight');
1162
+ highlightedCells.forEach(cell => cell.classList.remove('highlight'));
1163
+ }
1164
+
1165
+ // --- Message Box Functions ---
1166
+ let messageTimeoutId = null; // Store timeout ID for message box
1167
+ function showMessage(text, isError = false) {
1168
+ messageBox.textContent = text;
1169
+ messageBox.style.backgroundColor = isError ? 'var(--cell-active-kick)' : 'var(--button-active)';
1170
+ messageBox.style.color = isError ? 'var(--text-color)' : 'var(--background-color)';
1171
+ messageBox.style.display = 'block';
1172
+ // Clear any existing timeout
1173
+ if (messageTimeoutId) clearTimeout(messageTimeoutId);
1174
+ // Auto-hide message
1175
+ messageTimeoutId = setTimeout(hideMessage, 3500);
1176
+ }
1177
+
1178
+ function hideMessage() {
1179
+ messageBox.style.display = 'none';
1180
+ if (messageTimeoutId) {
1181
+ clearTimeout(messageTimeoutId);
1182
+ messageTimeoutId = null;
1183
+ }
1184
+ }
1185
+
1186
+ // --- Initialization ---
1187
+
1188
+ // Create the initial grid
1189
+ createGrid();
1190
+
1191
+ // Add event listeners using the interaction handlers
1192
+ playStopButton.addEventListener('touchstart', handlePlayStopInteraction, { passive: false });
1193
+ playStopButton.addEventListener('click', handlePlayStopInteraction);
1194
+ demoButton.addEventListener('touchstart', handleDemoInteraction, { passive: true });
1195
+ demoButton.addEventListener('click', handleDemoInteraction);
1196
+ recordButton.addEventListener('click', toggleRecording);
1197
+
1198
+ // Other control listeners
1199
+ tempoSlider.addEventListener('input', handleTempoChange);
1200
+ volumeSlider.addEventListener('input', handleVolumeChange);
1201
+ synthTypeSelector.addEventListener('change', handleSynthTypeChange);
1202
+ decaySlider.addEventListener('input', handleDecayChange);
1203
+ reverbSlider.addEventListener('input', handleReverbChange);
1204
+ drumSelectorContainer.addEventListener('click', handleDrumToolSelect);
1205
+
1206
+ // Grid size controls
1207
+ decreaseColsBtn.addEventListener('click', () => handleGridSizeChange(-1, 0));
1208
+ increaseColsBtn.addEventListener('click', () => handleGridSizeChange(1, 0));
1209
+ decreaseRowsBtn.addEventListener('click', () => handleGridSizeChange(0, -1));
1210
+ increaseRowsBtn.addEventListener('click', () => handleGridSizeChange(0, 1));
1211
+
1212
+ // Initial message
1213
+ showMessage("Click 'Play' or grid to start audio");
1214
+
1215
+ // Ensure audio stops when window is closed to prevent audio glitches
1216
+ window.addEventListener('beforeunload', () => {
1217
+ if (Tone.context.state !== 'closed') {
1218
+ Tone.context.close();
1219
+ }
1220
+ if (isRecording) {
1221
+ stopRecording();
1222
+ }
1223
+ });
1224
+
1225
+ </script>
1226
+ <p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - <a href="https://enzostvs-deepsite.hf.space?remix=SignorNessuno/loopstation" style="color: #fff;text-decoration: underline;" target="_blank" >🧬 Remix</a></p></body>
1227
+ </html>