-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
941 lines (822 loc) · 47 KB
/
Copy pathindex.html
File metadata and controls
941 lines (822 loc) · 47 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voice Perception Listening Test</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
.loading-bar {
transition: width 0.3s ease;
}
</style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-50 min-h-screen">
<div id="app"></div>
<script>
// ============= CONFIGURATION - UPDATE THESE =============
// Google Form Pre-filled URL Template
// Get this from: Google Form → ⋮ menu → Get pre-filled link
// The form should have "Collect email addresses" enabled in Settings
// Participants will manually check "Verified email" checkbox to receive responses
const GOOGLE_FORM_TEMPLATE = "https://docs.google.com/forms/d/e/1FAIpQLSd_MLDI7vuQN1c70_o5-szCioVbmrUKUKpHhtInxQ0tCnGREQ/viewform?usp=pp_url&entry.16675421=PARTICIPANT_ID&entry.623538109=TRIAL_NAME&entry.1036755193=LISTENING_DEVICE&entry.1172676033=MUSIC_BACKGROUND&entry.1771353994=LANGUAGE_BACKGROUND&entry.1783695746=FIRST_LANGUAGE&entry.1207484341=LANGUAGES_SPOKEN&entry.1419101100=AGE";
// GitHub repository details
const CONFIG = {
githubUser: 'yttehs',
githubRepo: 'Listening_Test',
githubBranch: 'main',
participantAssignmentsFile: 'participant_assignments.json'
};
// ========================================================
function getPrefilledFormURL() {
// Build URL with proper encoding
let url = GOOGLE_FORM_TEMPLATE;
// Get the trial display name (e.g., "Trial 1" instead of "Male_read_MG1_MG2")
const trialDisplayName = getTrialDisplayName();
// Replace each placeholder with actual values
// NOTE: Using LANGUAGES_SPOKEN to match the Google Form template
const replacements = {
'PARTICIPANT_ID': state.participantId,
'TRIAL_NAME': trialDisplayName, // Send "Trial 1" instead of full trial ID
'LISTENING_DEVICE': state.demographics.listeningDevice,
'MUSIC_BACKGROUND': state.demographics.musicBackground,
'LANGUAGE_BACKGROUND': state.demographics.languageBackground,
'FIRST_LANGUAGE': state.demographics.firstLanguage || 'N/A',
'LANGUAGES_SPOKEN': state.demographics.otherLanguages,
'AGE': state.demographics.age
};
console.log('=== FORM URL DEBUG ===');
console.log('Template URL:', GOOGLE_FORM_TEMPLATE);
console.log('Values to replace:', replacements);
// Replace each placeholder
for (const [placeholder, value] of Object.entries(replacements)) {
const beforeReplace = url;
url = url.replace(placeholder, encodeURIComponent(value));
if (beforeReplace === url) {
console.warn(`⚠️ Placeholder "${placeholder}" was NOT found in URL!`);
} else {
console.log(`✓ Replaced ${placeholder} with "${value}"`);
}
}
console.log('Final URL:', url);
console.log('======================');
return url;
}
// State management
let state = {
stage: 'start',
participantId: '',
participantEmail: '',
selectedTrial: '',
availableTrials: [],
participantAssignments: null,
demographics: {
listeningDevice: '',
musicBackground: '',
languageBackground: '',
firstLanguage: '',
otherLanguages: '',
age: ''
},
audioMapping: [],
positions: {},
playing: null,
dragging: null,
hovering: null,
loadingProgress: 0,
loadingMessage: 'Initializing...',
audioContext: null,
audioBuffers: {},
currentSource: null
};
const canvasSize = Math.min(window.innerWidth - 100, 800);
// Helper function to get trial display name
function getTrialDisplayName() {
if (!state.selectedTrial || !state.participantAssignments) {
return 'Trial';
}
const trialInfo = state.participantAssignments.trialInfo[state.selectedTrial];
return trialInfo && trialInfo.displayName ? trialInfo.displayName : 'Trial';
}
// Initialize
async function initialize() {
try {
const assignmentsUrl = `https://raw.githubusercontent.com/${CONFIG.githubUser}/${CONFIG.githubRepo}/${CONFIG.githubBranch}/${CONFIG.participantAssignmentsFile}`;
const response = await fetch(assignmentsUrl);
if (response.ok) {
state.participantAssignments = await response.json();
} else {
console.error('Could not load participant assignments');
state.participantAssignments = { participants: {}, trialInfo: {} };
}
} catch (error) {
console.error('Error loading participant assignments:', error);
state.participantAssignments = { participants: {}, trialInfo: {} };
}
render();
}
function loadTrialsForParticipant(participantId, email) {
if (!state.participantAssignments) {
return [];
}
const participant = state.participantAssignments.participants[participantId.toUpperCase()];
if (!participant) {
return [];
}
if (participant.email.toLowerCase() !== email.toLowerCase()) {
return [];
}
return participant.assignedTrials.map(trialId => {
const trialInfo = state.participantAssignments.trialInfo[trialId];
return {
id: trialId,
name: trialInfo && trialInfo.displayName ? trialInfo.displayName : trialId.replace(/_/g, " "),
numFiles: trialInfo ? trialInfo.numFiles : 24
};
});
}
function checkParticipantId() {
const participantInput = document.getElementById('participantId');
const emailInput = document.getElementById('participantEmail');
const trialSelectDiv = document.getElementById('trialSelectDiv');
const trialSelect = document.getElementById('trialSelect');
const participantError = document.getElementById('participantError');
const participantId = participantInput.value.trim().toUpperCase();
const email = emailInput.value.trim();
if (!participantId || !email) {
trialSelectDiv.style.display = 'none';
participantError.style.display = 'none';
return;
}
if (!state.participantAssignments || !state.participantAssignments.participants) {
participantError.style.display = 'block';
participantError.innerHTML = `
<div class="p-3 bg-red-50 border border-red-300 rounded-lg text-sm text-red-800">
<strong>Error:</strong> Participant assignments file not loaded. Please refresh the page or contact the researcher.
</div>
`;
trialSelectDiv.style.display = 'none';
return;
}
const assignedTrials = loadTrialsForParticipant(participantId, email);
if (assignedTrials.length === 0) {
participantError.style.display = 'block';
participantError.innerHTML = `
<div class="p-3 bg-red-50 border border-red-300 rounded-lg text-sm text-red-800">
<strong>Authentication Failed:</strong> Participant ID "${participantId}" and email "${email}" do not match our records. Please check both entries or contact the researcher.
</div>
`;
trialSelectDiv.style.display = 'none';
state.availableTrials = [];
} else {
participantError.style.display = 'none';
trialSelectDiv.style.display = 'block';
state.availableTrials = assignedTrials;
state.participantEmail = email;
const trialsOptions = assignedTrials.map(trial =>
`<option value="${trial.id}">${trial.name} (${trial.numFiles} samples)</option>`
).join('');
trialSelect.innerHTML = '<option value="">-- Select a trial --</option>' + trialsOptions;
}
}
function render() {
const app = document.getElementById('app');
switch(state.stage) {
case 'start':
app.innerHTML = renderStart();
break;
case 'loading':
app.innerHTML = renderLoading();
break;
case 'instructions':
app.innerHTML = renderInstructions();
break;
case 'test':
app.innerHTML = renderTest();
setTimeout(drawCanvas, 0);
break;
case 'complete':
app.innerHTML = renderComplete();
break;
}
}
function renderStart() {
return `
<div class="p-8">
<div class="max-w-2xl mx-auto bg-white rounded-xl shadow-lg p-8">
<h1 class="text-3xl font-bold text-gray-800 mb-6">Voice Perception Listening Test</h1>
<div class="mb-6 p-4 bg-blue-50 rounded-lg">
<div class="flex items-start gap-3">
<svg class="w-5 h-5 text-blue-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<div class="text-sm text-gray-700">
<p class="font-semibold mb-2">Welcome!</p>
<p class="mb-2">In this test, you will listen to voice samples and arrange them in the space provided based on how similar they sound to you.</p>
<p>The test will take approximately 15-20 minutes to complete.</p>
</div>
</div>
</div>
<div class="mb-6">
<label class="block text-sm font-medium text-gray-700 mb-2">Participant ID *</label>
<input
type="text"
id="participantId"
value="${state.participantId}"
placeholder="Enter your participant ID (e.g., P001)"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
/>
</div>
<div class="mb-6">
<label class="block text-sm font-medium text-gray-700 mb-2">Email Address *</label>
<input
type="email"
id="participantEmail"
value="${state.participantEmail}"
placeholder="Enter your email address"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
/>
<p class="text-xs text-gray-500 mt-1">Use the same email provided by the researcher</p>
</div>
<button
onclick="checkParticipantId()"
class="mb-6 px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors font-medium"
>
Verify & Load Trials
</button>
<div id="participantError" style="display: none;" class="mb-6"></div>
<div id="trialSelectDiv" style="display: none;" class="mb-6">
<label class="block text-sm font-medium text-gray-700 mb-2">Select Trial *</label>
<select id="trialSelect" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
<option value="">-- Select a trial --</option>
</select>
<p class="text-xs text-gray-500 mt-2">These are the trials assigned to you.</p>
</div>
<div class="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-300">
<h3 class="font-semibold text-gray-800 mb-4">Background Information</h3>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Listening Device *</label>
<select id="listeningDevice" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
<option value="">-- Select --</option>
<option value="headphones">Headphones</option>
<option value="earphones">Earphones</option>
<option value="speakers">Speakers</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Do you have a background in music? *</label>
<select id="musicBackground" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
<option value="">-- Select --</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Language Background *</label>
<select id="languageBackground" onchange="toggleFirstLanguage()" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
<option value="">-- Select --</option>
<option value="native">Native English Speaker</option>
<option value="non-native">Non-Native English Speaker</option>
</select>
</div>
<div id="firstLanguageDiv" style="display: none;">
<label class="block text-sm font-medium text-gray-700 mb-2">What is your first language? *</label>
<input type="text" id="firstLanguage" placeholder="e.g., Spanish, Mandarin, Hindi" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">What languages do you speak? *</label>
<input type="text" id="otherLanguages" placeholder="e.g., English, Spanish, French" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Age *</label>
<input type="number" id="age" placeholder="Enter your age" min="18" max="100" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"/>
</div>
</div>
</div>
<button onclick="validateAndStart()" id="loadButton" class="w-full bg-indigo-600 text-white py-3 rounded-lg hover:bg-indigo-700 transition-colors font-medium">
Load Audio Files & Continue
</button>
</div>
</div>
`;
}
function toggleFirstLanguage() {
const langBg = document.getElementById('languageBackground').value;
const firstLangDiv = document.getElementById('firstLanguageDiv');
firstLangDiv.style.display = langBg === 'non-native' ? 'block' : 'none';
}
function validateAndStart() {
state.participantId = document.getElementById('participantId').value.trim().toUpperCase();
state.participantEmail = document.getElementById('participantEmail').value.trim();
state.selectedTrial = document.getElementById('trialSelect').value;
state.demographics.listeningDevice = document.getElementById('listeningDevice').value;
state.demographics.musicBackground = document.getElementById('musicBackground').value;
state.demographics.languageBackground = document.getElementById('languageBackground').value;
state.demographics.firstLanguage = document.getElementById('firstLanguage').value.trim();
state.demographics.otherLanguages = document.getElementById('otherLanguages').value.trim();
state.demographics.age = document.getElementById('age').value;
if (!state.participantId) {
alert('Please enter a participant ID');
return;
}
if (!state.participantEmail) {
alert('Please enter your email address');
return;
}
if (!state.participantAssignments || !state.participantAssignments.participants[state.participantId]) {
alert('Invalid Participant ID. Please verify your ID and email.');
return;
}
const participant = state.participantAssignments.participants[state.participantId];
if (participant.email.toLowerCase() !== state.participantEmail.toLowerCase()) {
alert('Email address does not match the Participant ID. Please check both entries.');
return;
}
if (!state.selectedTrial) {
alert('Please select a trial');
return;
}
if (!participant.assignedTrials.includes(state.selectedTrial)) {
alert('This trial is not assigned to you. Please select from your assigned trials.');
return;
}
if (!state.demographics.listeningDevice) {
alert('Please select your listening device');
return;
}
if (!state.demographics.musicBackground) {
alert('Please indicate if you have a music background');
return;
}
if (!state.demographics.languageBackground) {
alert('Please select your language background');
return;
}
if (state.demographics.languageBackground === 'non-native' && !state.demographics.firstLanguage) {
alert('Please enter your first language');
return;
}
if (!state.demographics.otherLanguages) {
alert('Please list the languages you speak');
return;
}
if (!state.demographics.age || state.demographics.age < 18) {
alert('Please enter a valid age (18 or older)');
return;
}
startLoading();
}
function renderLoading() {
return `
<div class="p-8 flex items-center justify-center min-h-screen">
<div class="max-w-md mx-auto bg-white rounded-xl shadow-lg p-8 text-center">
<svg class="w-16 h-16 text-indigo-600 mx-auto mb-4 animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"></path>
</svg>
<h2 class="text-2xl font-bold text-gray-800 mb-4">${state.loadingMessage}</h2>
<div class="w-full bg-gray-200 rounded-full h-4 mb-2">
<div class="loading-bar bg-indigo-600 h-4 rounded-full" style="width: ${state.loadingProgress}%"></div>
</div>
<p class="text-gray-600">${state.loadingProgress}% complete</p>
<p class="text-sm text-gray-500 mt-4">Please wait while we load the voice samples...</p>
<p class="text-sm font-medium text-indigo-600 mt-2">${getTrialDisplayName()}</p>
</div>
</div>
`;
}
function renderInstructions() {
const numSamples = state.audioMapping.length;
return `
<div class="p-8">
<div class="max-w-3xl mx-auto bg-white rounded-xl shadow-lg p-8">
<div class="mb-4 p-3 bg-indigo-100 rounded-lg">
<p class="text-sm font-medium text-indigo-800">
${getTrialDisplayName()} | Participant: ${state.participantId}
</p>
</div>
<h1 class="text-3xl font-bold text-gray-800 mb-6">Test Instructions</h1>
<div class="space-y-4 text-gray-700 mb-8">
<div class="p-4 bg-red-50 rounded-lg border-2 border-red-300">
<h3 class="font-semibold text-red-900 mb-2">⚠️ Important Listening Environment</h3>
<ul class="list-disc list-inside space-y-1 text-sm">
<li><strong>Take this test in a quiet room</strong> with minimal background noise</li>
<li>Ensure your ${state.demographics.listeningDevice} are properly connected and working</li>
<li><strong>Set your volume to a comfortable level at the start</strong> and keep it constant throughout the test</li>
<li><strong>Listen to all voices at the same volume</strong> - do not adjust volume between samples</li>
</ul>
</div>
<div class="p-4 bg-yellow-50 rounded-lg border-2 border-yellow-300">
<h3 class="font-semibold text-yellow-900 mb-2">🎯 What to Focus On</h3>
<p class="text-sm mb-2">
<strong>Your task is to judge how the voices SOUND, not what they are saying.</strong>
</p>
<ul class="list-disc list-inside space-y-1 text-sm">
<li>The voice samples may be incomplete sentence fragments (1-1.5 seconds long)</li>
<li>Focus on voice quality, tone, pitch, and overall sound characteristics</li>
<li><strong>Ignore the linguistic content</strong> - different speakers may say different things</li>
<li>Base your judgments purely on acoustic similarity of the voices</li>
</ul>
</div>
<div class="p-4 bg-indigo-50 rounded-lg">
<h2 class="font-semibold text-lg mb-2">Your Task:</h2>
<p>You will arrange ${numSamples} voice samples (numbered 1-${numSamples}) in a space provided based on how similar they sound to you.</p>
</div>
<div class="p-4 bg-gray-50 rounded-lg">
<h3 class="font-semibold mb-2">How to arrange voices:</h3>
<ul class="list-disc list-inside space-y-2">
<li><strong>Similar-sounding voices</strong> → Place them close together (can even overlap)</li>
<li><strong>Different-sounding voices</strong> → Place them far apart</li>
<li><strong>Use the entire space</strong> - spread voices across the full canvas area</li>
<li>If voices sound very similar, you can place them on top of each other</li>
</ul>
</div>
<div class="p-4 bg-gray-50 rounded-lg">
<h3 class="font-semibold mb-2">Controls:</h3>
<ul class="list-disc list-inside space-y-2">
<li><strong>Click</strong> a numbered circle to play that voice sample</li>
<li><strong>Drag</strong> circles to reposition them in the space</li>
<li>The circle turns <span class="text-green-600 font-semibold">green</span> when playing audio</li>
<li>Listen to samples as many times as you need</li>
<li>Take your time - there are no wrong answers</li>
</ul>
</div>
<div class="p-4 bg-blue-50 rounded-lg border border-blue-200">
<p class="text-sm">
<strong>Remember:</strong> Your perception is subjective and valuable.
Arrange the voices based on how they SOUND to YOU, not what they are saying.
</p>
</div>
</div>
<button onclick="startTest()" class="w-full bg-indigo-600 text-white py-3 rounded-lg hover:bg-indigo-700 transition-colors font-medium text-lg">
Start Test
</button>
</div>
</div>
`;
}
function renderTest() {
return `
<div class="p-8">
<div class="max-w-6xl mx-auto">
<div class="bg-white rounded-xl shadow-lg p-6 mb-6">
<div class="flex justify-between items-center mb-4">
<div>
<h1 class="text-2xl font-bold text-gray-800">Voice Arrangement Task</h1>
<p class="text-gray-600">Participant: ${state.participantId} | ${getTrialDisplayName()}</p>
</div>
<div class="flex gap-2">
<button onclick="resetPositions()" class="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
</svg>
Reset
</button>
<button onclick="completeTest()" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium">
Complete Test
</button>
</div>
</div>
</div>
<div class="bg-white rounded-xl shadow-lg p-6">
<div class="mb-4 p-3 bg-blue-50 rounded-lg">
<p class="text-sm text-gray-700">
<strong>Click</strong> circles to play audio • <strong>Drag</strong> circles to arrange •
<span class="ml-2 inline-flex items-center gap-1">
<span class="w-3 h-3 bg-green-500 rounded-full"></span> = Playing
</span>
</p>
</div>
<canvas id="canvas" width="${canvasSize}" height="${canvasSize}" class="cursor-pointer border border-gray-300 rounded-lg mx-auto block"></canvas>
<p class="text-sm text-gray-500 mt-4 text-center">
Similar voices should be close together. Different voices should be far apart.
</p>
</div>
</div>
</div>
`;
}
function renderComplete() {
return `
<div class="p-8">
<div class="max-w-2xl mx-auto bg-white rounded-xl shadow-lg p-8">
<div class="text-center mb-8">
<div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
<svg class="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
</svg>
</div>
<h1 class="text-3xl font-bold text-gray-800 mb-2">Test Complete!</h1>
<p class="text-gray-600">Thank you for completing the test, ${state.participantId}</p>
<p class="text-sm text-gray-500 mt-2">${getTrialDisplayName()}</p>
</div>
<div class="space-y-4">
<div class="p-4 bg-gray-50 rounded-lg">
<h2 class="font-semibold mb-2">Results Summary:</h2>
<ul class="text-sm text-gray-700 space-y-1">
<li>• Voice samples arranged: ${state.audioMapping.length}</li>
<li>• Unique pairwise distances: ${(state.audioMapping.length * (state.audioMapping.length - 1)) / 2}</li>
<li>• Coordinates normalized to 0-1 scale</li>
</ul>
</div>
<div class="p-4 bg-blue-50 rounded-lg border-2 border-blue-300">
<h3 class="font-semibold text-blue-900 mb-3">📤 Submit Your Results</h3>
<p class="text-sm text-gray-700 mb-3">
Please follow these steps to submit your results:
</p>
<ol class="text-sm text-gray-700 space-y-2 mb-4 list-decimal list-inside">
<li><strong>Download both files</strong> using the buttons below</li>
<li><strong>Open the pre-filled submission form</strong> (your demographic info is already filled in!)</li>
<li><strong>Check the "Email" checkbox</strong> to receive a copy of your responses</li>
<li><strong>Upload both files</strong> to the form and submit</li>
</ol>
<div class="space-y-2 mb-4">
<button
onclick="exportResults()"
class="w-full flex items-center justify-center gap-2 bg-indigo-600 text-white py-3 rounded-lg hover:bg-indigo-700 transition-colors font-medium"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
</svg>
1. Download JSON File
</button>
<button
onclick="exportCSV()"
class="w-full flex items-center justify-center gap-2 bg-green-600 text-white py-3 rounded-lg hover:bg-green-700 transition-colors font-medium"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
</svg>
2. Download CSV File
</button>
</div>
<button
onclick="window.open(getPrefilledFormURL(), '_blank')"
class="w-full flex items-center justify-center gap-2 bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-colors font-medium"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
</svg>
3. Open Submission Form (Pre-filled)
</button>
</div>
<div class="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
<p class="text-sm text-gray-700">
<strong>Important:</strong> Your demographic information is pre-filled in the form.
Please check the "Email" box to receive a copy of your submission, so that you can keep track of the completed trials.
</p>
</div>
<div class="pt-4 border-t border-gray-200">
<button
onclick="window.location.reload()"
class="w-full text-indigo-600 hover:text-indigo-800 transition-colors py-2 font-medium"
>
Complete Another Trial
</button>
</div>
</div>
</div>
</div>
`;
}
// Core functions
async function startLoading() {
state.stage = 'loading';
render();
try {
await loadConfiguration();
await loadAudioFiles();
initializePositions();
state.stage = 'instructions';
render();
} catch (error) {
console.error('Error during loading:', error);
alert('Error loading audio files. Please check your internet connection and try again.\n\nError: ' + error.message);
state.stage = 'start';
render();
}
}
async function loadConfiguration() {
state.loadingMessage = 'Loading configuration...';
render();
const configUrl = `https://raw.githubusercontent.com/${CONFIG.githubUser}/${CONFIG.githubRepo}/${CONFIG.githubBranch}/${state.selectedTrial}/config.json`;
const response = await fetch(configUrl);
if (!response.ok) {
throw new Error(`Configuration file not found for trial: ${state.selectedTrial}`);
}
const config = await response.json();
state.audioMapping = config.audioFiles;
}
async function loadAudioFiles() {
state.loadingMessage = 'Loading audio files...';
if (!state.audioContext) {
state.audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
for (let idx = 0; idx < state.audioMapping.length; idx++) {
const audioUrl = state.audioMapping[idx].url;
const response = await fetch(audioUrl);
if (!response.ok) {
throw new Error(`Failed to load ${state.audioMapping[idx].filename}`);
}
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await state.audioContext.decodeAudioData(arrayBuffer);
state.audioBuffers[idx] = audioBuffer;
state.loadingProgress = Math.round(((idx + 1) / state.audioMapping.length) * 100);
render();
}
}
function initializePositions() {
state.positions = {};
for (let i = 0; i < state.audioMapping.length; i++) {
state.positions[i] = {
x: 0.1 + Math.random() * 0.8,
y: 0.1 + Math.random() * 0.8
};
}
}
function startTest() {
state.stage = 'test';
render();
setupCanvas();
}
function setupCanvas() {
const canvas = document.getElementById('canvas');
if (!canvas) return;
canvas.addEventListener('mousedown', handleMouseDown);
canvas.addEventListener('mousemove', handleMouseMove);
canvas.addEventListener('mouseup', handleMouseUp);
canvas.addEventListener('mouseleave', handleMouseUp);
}
function handleMouseDown(e) {
const canvas = document.getElementById('canvas');
const rect = canvas.getBoundingClientRect();
const x = (e.clientX - rect.left) / rect.width;
const y = (e.clientY - rect.top) / rect.height;
for (let i = 0; i < state.audioMapping.length; i++) {
const pos = state.positions[i];
const dist = Math.sqrt(Math.pow(x - pos.x, 2) + Math.pow(y - pos.y, 2));
if (dist < 0.025) {
setTimeout(() => {
if (state.dragging === null) {
togglePlay(i);
}
}, 100);
state.dragging = i;
return;
}
}
}
function handleMouseMove(e) {
const canvas = document.getElementById('canvas');
const rect = canvas.getBoundingClientRect();
const x = (e.clientX - rect.left) / rect.width;
const y = (e.clientY - rect.top) / rect.height;
if (state.dragging !== null) {
const clampedX = Math.max(0, Math.min(1, x));
const clampedY = Math.max(0, Math.min(1, y));
state.positions[state.dragging] = { x: clampedX, y: clampedY };
drawCanvas();
} else {
let hoverFound = null;
for (let i = 0; i < state.audioMapping.length; i++) {
const pos = state.positions[i];
const dist = Math.sqrt(Math.pow(x - pos.x, 2) + Math.pow(y - pos.y, 2));
if (dist < 0.025) {
hoverFound = i;
break;
}
}
if (state.hovering !== hoverFound) {
state.hovering = hoverFound;
drawCanvas();
}
}
}
function handleMouseUp() {
state.dragging = null;
}
function togglePlay(id) {
if (state.currentSource) {
state.currentSource.stop();
state.currentSource = null;
}
if (state.playing === id) {
state.playing = null;
drawCanvas();
return;
}
const audioBuffer = state.audioBuffers[id];
if (!audioBuffer) return;
const source = state.audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(state.audioContext.destination);
source.onended = () => {
state.playing = null;
state.currentSource = null;
drawCanvas();
};
source.start(0);
state.currentSource = source;
state.playing = id;
drawCanvas();
}
function drawCanvas() {
const canvas = document.getElementById('canvas');
if (!canvas) return;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = '#9ca3af';
ctx.lineWidth = 2;
ctx.strokeRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < state.audioMapping.length; i++) {
const pos = state.positions[i];
const x = pos.x * canvas.width;
const y = pos.y * canvas.height;
let fillColor = '#6366f1';
if (state.playing === i) {
fillColor = '#10b981';
} else if (state.dragging === i) {
fillColor = '#3b82f6';
} else if (state.hovering === i) {
fillColor = '#818cf8';
}
ctx.fillStyle = fillColor;
ctx.beginPath();
ctx.arc(x, y, 25, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = 'white';
ctx.font = 'bold 16px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(i + 1, x, y);
}
}
function resetPositions() {
initializePositions();
drawCanvas();
}
function completeTest() {
if (state.currentSource) {
state.currentSource.stop();
state.currentSource = null;
}
state.stage = 'complete';
render();
}
function calculateDistances() {
const distances = [];
for (let i = 0; i < state.audioMapping.length; i++) {
for (let j = i + 1; j < state.audioMapping.length; j++) {
const pos1 = state.positions[i];
const pos2 = state.positions[j];
const dist = Math.sqrt(
Math.pow(pos2.x - pos1.x, 2) + Math.pow(pos2.y - pos1.y, 2)
);
distances.push({
voice1: i + 1,
voice2: j + 1,
distance: dist.toFixed(6)
});
}
}
return distances;
}
function exportResults() {
const results = {
participantId: state.participantId,
participantEmail: state.participantEmail,
trialId: state.selectedTrial,
timestamp: new Date().toISOString(),
demographics: state.demographics,
positions: state.audioMapping.map((audio, i) => ({
circle: i + 1,
filename: audio.filename,
x: state.positions[i].x.toFixed(6),
y: state.positions[i].y.toFixed(6)
})),
distances: calculateDistances()
};
const blob = new Blob([JSON.stringify(results, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `voice_perception_${state.participantId}_${state.selectedTrial}_${Date.now()}.json`;
a.click();
}
function exportCSV() {
const distances = calculateDistances();
const csv = [
'Participant ID,Participant Email,Trial ID,Voice 1,Voice 2,Distance',
...distances.map(d => `${state.participantId},${state.participantEmail},${state.selectedTrial},${d.voice1},${d.voice2},${d.distance}`)
].join('\n');
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `voice_perception_${state.participantId}_${state.selectedTrial}_${Date.now()}.csv`;
a.click();
}
initialize();
</script>
</body>
</html>