-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js.old
More file actions
1914 lines (1594 loc) · 68.3 KB
/
script.js.old
File metadata and controls
1914 lines (1594 loc) · 68.3 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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// メトロノームクラス
class Metronome {
constructor() {
this.audioContext = null;
this.isPlaying = false;
this.currentBeat = 0;
this.totalBeats = 0; // 振り子アニメーション用のグローバルカウンター
// デフォルト設定
this.defaults = {
tempo: 120,
beatsPerBar: 4,
volume: 70,
soundType: 'click',
rhythmPattern: 'simple',
animationType: 'pendulum'
};
// 保存された設定を読み込むか、デフォルトを使用
this.tempo = parseInt(localStorage.getItem('tempo')) || this.defaults.tempo;
this.beatsPerBar = parseInt(localStorage.getItem('beatsPerBar')) || this.defaults.beatsPerBar;
this.volume = (parseInt(localStorage.getItem('volume')) || this.defaults.volume) / 100;
this.soundType = localStorage.getItem('soundType') || this.defaults.soundType;
this.rhythmPattern = localStorage.getItem('rhythmPattern') || this.defaults.rhythmPattern;
this.animationType = localStorage.getItem('animationType') || this.defaults.animationType;
this.subdivisionSound = localStorage.getItem('subdivisionSound') === 'true';
this.subdivisionVolume = (parseInt(localStorage.getItem('subdivisionVolume')) || 50) / 100;
this.noteTime = 0.0;
this.scheduleAheadTime = 0.1;
this.nextNoteTime = 0.0;
this.timerID = null;
// タップテンポ用
this.tapTimes = [];
this.tapTimeout = null;
// タイマー機能
this.timerEnabled = false;
this.timerMinutes = 0;
this.timerSeconds = 0;
this.timerRemaining = 0; // 残り時間(秒)
this.timerInterval = null;
// カスタムプリセット
this.customPresets = this.loadCustomPresets();
this.activePresetId = null;
this.initAudioContext();
this.loadSettings();
this.initEventListeners();
this.renderPresetsList();
}
initAudioContext() {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
// 設定を読み込んでUIに反映
loadSettings() {
this.setTempo(this.tempo);
this.setBeatsPerBar(this.beatsPerBar);
this.setVolume(this.volume * 100);
document.getElementById('beatsPerBar').value = this.beatsPerBar;
document.getElementById('soundType').value = this.soundType;
document.getElementById('rhythmPattern').value = this.rhythmPattern;
document.getElementById('animationType').value = this.animationType;
document.getElementById('subdivisionSound').checked = this.subdivisionSound;
this.setSubdivisionVolume(this.subdivisionVolume * 100);
this.toggleSubdivisionVolumeControl();
this.setAnimationType(this.animationType);
}
// 設定を保存
saveSettings() {
localStorage.setItem('tempo', this.tempo);
localStorage.setItem('beatsPerBar', this.beatsPerBar);
localStorage.setItem('volume', Math.round(this.volume * 100));
localStorage.setItem('soundType', this.soundType);
localStorage.setItem('rhythmPattern', this.rhythmPattern);
localStorage.setItem('animationType', this.animationType);
localStorage.setItem('subdivisionSound', this.subdivisionSound);
localStorage.setItem('subdivisionVolume', Math.round(this.subdivisionVolume * 100));
}
// 設定をリセット
resetSettings() {
if (this.isPlaying) {
this.stop();
}
this.tempo = this.defaults.tempo;
this.beatsPerBar = this.defaults.beatsPerBar;
this.volume = this.defaults.volume / 100;
this.soundType = this.defaults.soundType;
this.rhythmPattern = this.defaults.rhythmPattern;
this.animationType = this.defaults.animationType;
this.subdivisionSound = false;
this.subdivisionVolume = 0.5;
this.loadSettings();
this.saveSettings();
}
// 音を生成
playSound(time, isAccent = false, isSubdivision = false) {
const osc = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
osc.connect(gainNode);
gainNode.connect(this.audioContext.destination);
// 細分化された音の場合、別の音を使用
if (isSubdivision && this.subdivisionSound) {
// 弱拍専用の音(より低く、短く、音量は調整可能)
switch(this.soundType) {
case 'click':
osc.frequency.value = 400;
gainNode.gain.value = this.volume * this.subdivisionVolume;
osc.type = 'sine';
break;
case 'beep':
osc.frequency.value = 220;
gainNode.gain.value = this.volume * this.subdivisionVolume;
osc.type = 'square';
break;
case 'wood':
osc.frequency.value = 100;
gainNode.gain.value = this.volume * this.subdivisionVolume * 0.8;
osc.type = 'triangle';
break;
case 'cowbell':
osc.frequency.value = 200;
gainNode.gain.value = this.volume * this.subdivisionVolume;
osc.type = 'square';
break;
}
} else {
// 通常の音色に応じた周波数設定
switch(this.soundType) {
case 'click':
osc.frequency.value = isAccent ? 1000 : 800;
gainNode.gain.value = this.volume * (isAccent ? 1.5 : 1);
osc.type = 'sine';
break;
case 'beep':
osc.frequency.value = isAccent ? 880 : 440;
gainNode.gain.value = this.volume;
osc.type = 'square';
break;
case 'wood':
osc.frequency.value = isAccent ? 220 : 180;
gainNode.gain.value = this.volume * 0.8;
osc.type = 'triangle';
break;
case 'cowbell':
osc.frequency.value = isAccent ? 540 : 400;
gainNode.gain.value = this.volume * 0.9;
osc.type = 'square';
break;
}
}
// エンベロープ設定
const attackTime = 0.001;
const releaseTime = isSubdivision && this.subdivisionSound ? 0.03 : 0.05; // 弱拍は短く
gainNode.gain.setValueAtTime(gainNode.gain.value, time);
gainNode.gain.exponentialRampToValueAtTime(0.01, time + releaseTime);
osc.start(time);
osc.stop(time + releaseTime);
}
// リズムパターンに基づいて音を再生(共通ロジック)
playRhythmPattern(beatNumber, time) {
const isAccent = (beatNumber % this.beatsPerBar === 0);
switch(this.rhythmPattern) {
case 'simple':
this.playSound(time, isAccent, false);
break;
case 'eighth':
this.playSound(time, isAccent, false);
this.playSound(time + (60.0 / this.tempo) / 2, false, true); // 弱拍
break;
case 'triplet':
this.playSound(time, isAccent, false);
this.playSound(time + (60.0 / this.tempo) / 3, false, true); // 弱拍
this.playSound(time + (60.0 / this.tempo) * 2 / 3, false, true); // 弱拍
break;
case 'sixteenth':
for(let i = 0; i < 4; i++) {
this.playSound(time + (60.0 / this.tempo) * i / 4, isAccent && i === 0, i > 0); // i > 0は弱拍
}
break;
case 'sextuplet':
for(let i = 0; i < 6; i++) {
this.playSound(time + (60.0 / this.tempo) * i / 6, isAccent && i === 0, i > 0); // i > 0は弱拍
}
break;
}
}
// リズムパターンに基づいたスケジュール
scheduleNote(beatNumber, time) {
const isAccent = (beatNumber % this.beatsPerBar === 0);
// 音を再生
this.playRhythmPattern(beatNumber, time);
// ビジュアルフィードバック
const delay = (time - this.audioContext.currentTime) * 1000;
const totalBeatCount = this.totalBeats; // 現在のグローバル拍数をキャプチャ
setTimeout(() => {
this.updateVisuals(isAccent, beatNumber, totalBeatCount);
}, delay);
// グローバルカウンターをインクリメント
this.totalBeats++;
}
// 次のノートをスケジュール
scheduler() {
while (this.nextNoteTime < this.audioContext.currentTime + this.scheduleAheadTime) {
this.scheduleNote(this.currentBeat, this.nextNoteTime);
this.nextNote();
}
}
nextNote() {
const secondsPerBeat = 60.0 / this.tempo;
this.nextNoteTime += secondsPerBeat;
this.currentBeat++;
if (this.currentBeat >= this.beatsPerBar) {
this.currentBeat = 0;
}
}
start() {
if (this.isPlaying) return;
if (!this.audioContext) {
this.initAudioContext();
}
if (this.audioContext.state === 'suspended') {
this.audioContext.resume();
}
this.isPlaying = true;
this.currentBeat = 0;
this.totalBeats = 0;
this.nextNoteTime = this.audioContext.currentTime;
// 1拍目を即座に再生(音とビジュアル)
this.playRhythmPattern(0, this.audioContext.currentTime);
this.updateVisuals(true, 0, 1); // totalBeatCount=1で右側に動かす
// totalBeatsは0のまま(次のscheduleNoteで1になる)
// 次の拍のスケジュール時間を設定
const secondsPerBeat = 60.0 / this.tempo;
this.nextNoteTime += secondsPerBeat;
this.currentBeat = 1; // 次は2拍目から
this.timerID = setInterval(() => this.scheduler(), 25);
// タイマーが有効な場合、カウントダウンを開始
if (this.timerEnabled) {
this.startTimer();
}
this.updatePlayButton();
}
stop() {
if (!this.isPlaying) return;
this.isPlaying = false;
clearInterval(this.timerID);
this.currentBeat = 0;
this.totalBeats = 0;
// タイマーを停止
this.stopTimer();
this.updatePlayButton();
this.resetVisuals();
}
toggle() {
if (this.isPlaying) {
this.stop();
} else {
this.start();
}
}
setTempo(bpm) {
// 小数点第一位まで対応(1.0〜300.0)
this.tempo = Math.max(1, Math.min(300, parseFloat(bpm)));
// スライダーは整数のみ(小数点は反映しない)
document.getElementById('tempoSlider').value = Math.round(this.tempo);
// 入力とBPM表示は小数点第一位まで表示
const tempoDisplay = Number.isInteger(this.tempo) ? this.tempo : this.tempo.toFixed(1);
document.getElementById('tempoInput').value = tempoDisplay;
document.getElementById('bpm-display').textContent = tempoDisplay;
this.saveSettings();
}
setBeatsPerBar(beats) {
this.beatsPerBar = parseInt(beats);
this.currentBeat = 0;
this.updateBeatIndicator();
this.saveSettings();
}
setVolume(vol) {
this.volume = vol / 100;
document.getElementById('volumeValue').textContent = vol + '%';
this.saveSettings();
}
setSubdivisionVolume(vol) {
this.subdivisionVolume = vol / 100;
document.getElementById('subdivisionVolumeSlider').value = vol;
document.getElementById('subdivisionVolumeValue').textContent = vol + '%';
this.saveSettings();
}
toggleSubdivisionVolumeControl() {
const control = document.getElementById('subdivisionVolumeControl');
if (this.subdivisionSound) {
control.style.display = 'block';
} else {
control.style.display = 'none';
}
}
setSoundType(type) {
this.soundType = type;
this.saveSettings();
}
setRhythmPattern(pattern) {
this.rhythmPattern = pattern;
this.saveSettings();
}
setAnimationType(type) {
this.animationType = type;
// アニメーションクラスをリセット
const visualDisplay = document.querySelector('.visual-display');
visualDisplay.classList.remove('pulse-mode', 'flash-mode');
if (type === 'pulse') {
visualDisplay.classList.add('pulse-mode');
} else if (type === 'flash') {
visualDisplay.classList.add('flash-mode');
}
this.saveSettings();
}
// ビジュアル更新
updateVisuals(isAccent, beatNumber, totalBeatCount) {
this.updateBeatIndicator(beatNumber);
const visualDisplay = document.querySelector('.visual-display');
const bpmDisplay = document.getElementById('bpm-display');
const pendulum = document.getElementById('pendulum');
switch(this.animationType) {
case 'pendulum':
const maxAngle = 30;
// グローバルカウンターで左右交互に振る(小節をまたいでも連続)
// 初期位置を左側(-30deg)にするため、偶数で左(-1)、奇数で右(1)
const direction = totalBeatCount % 2 === 0 ? -1 : 1;
const angle = maxAngle * direction;
// トランジション時間を拍の長さに合わせる
const beatDuration = 60.0 / this.tempo;
pendulum.style.transition = `transform ${beatDuration}s linear`;
pendulum.style.transform = `rotate(${angle}deg)`;
if (isAccent) {
pendulum.classList.add('accent');
setTimeout(() => pendulum.classList.remove('accent'), 300);
}
break;
case 'pulse':
bpmDisplay.classList.add('pulse');
setTimeout(() => bpmDisplay.classList.remove('pulse'), 200);
break;
case 'flash':
if (isAccent) {
bpmDisplay.classList.add('flash');
setTimeout(() => bpmDisplay.classList.remove('flash'), 150);
}
visualDisplay.classList.add('flash-active');
setTimeout(() => visualDisplay.classList.remove('flash-active'), 100);
break;
}
}
resetVisuals() {
const pendulum = document.getElementById('pendulum');
pendulum.style.transform = 'rotate(-30deg)'; // 初期位置を左側に
pendulum.classList.remove('accent');
const bpmDisplay = document.getElementById('bpm-display');
bpmDisplay.classList.remove('pulse', 'flash');
const visualDisplay = document.querySelector('.visual-display');
visualDisplay.classList.remove('flash-active');
this.updateBeatIndicator();
}
updateBeatIndicator(beatNumber) {
const indicator = document.getElementById('beat-indicator');
if (beatNumber !== undefined) {
// 再生中で特定のビート番号が指定された場合
const currentBeatDisplay = beatNumber + 1;
indicator.textContent = `${currentBeatDisplay}/${this.beatsPerBar}`;
} else {
// 停止中や初期化時
indicator.textContent = `1/${this.beatsPerBar}`;
}
}
updatePlayButton() {
const playBtn = document.getElementById('playBtn');
const playIcon = document.getElementById('playIcon');
if (this.isPlaying) {
playBtn.classList.add('playing');
playIcon.textContent = '■';
} else {
playBtn.classList.remove('playing');
playIcon.textContent = '▶';
}
}
// タップテンポ機能
handleTap() {
const now = Date.now();
this.tapTimes.push(now);
// 2秒以上前のタップを削除
this.tapTimes = this.tapTimes.filter(time => now - time < 2000);
// タップタイムアウトをリセット
if (this.tapTimeout) {
clearTimeout(this.tapTimeout);
}
this.tapTimeout = setTimeout(() => {
this.tapTimes = [];
}, 2000);
// 最低2回のタップが必要
if (this.tapTimes.length >= 2) {
const intervals = [];
for (let i = 1; i < this.tapTimes.length; i++) {
intervals.push(this.tapTimes[i] - this.tapTimes[i - 1]);
}
const avgInterval = intervals.reduce((a, b) => a + b) / intervals.length;
const bpm = Math.round(60000 / avgInterval);
this.setTempo(bpm);
}
}
// タイマー機能
startTimer() {
// 残り時間を計算(分と秒から秒数に変換)
this.timerRemaining = this.timerMinutes * 60 + this.timerSeconds;
if (this.timerRemaining <= 0) {
return;
}
this.updateTimerDisplay();
// 1秒ごとにカウントダウン
this.timerInterval = setInterval(() => {
this.timerRemaining--;
this.updateTimerDisplay();
// 残り10秒以下で警告表示
const timerDisplay = document.getElementById('timerDisplayHeader');
if (this.timerRemaining <= 10 && this.timerRemaining > 0) {
timerDisplay.classList.add('warning');
}
// タイマー終了
if (this.timerRemaining <= 0) {
this.onTimerComplete();
}
}, 1000);
}
stopTimer() {
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
const timerDisplay = document.getElementById('timerDisplayHeader');
timerDisplay.classList.remove('warning');
// タイマーを初期表示に戻す
if (this.timerEnabled) {
const totalSeconds = this.timerMinutes * 60 + this.timerSeconds;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
timerDisplay.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
} else {
timerDisplay.textContent = '--:--';
}
}
updateTimerDisplay() {
const minutes = Math.floor(this.timerRemaining / 60);
const seconds = this.timerRemaining % 60;
const timerDisplay = document.getElementById('timerDisplayHeader');
timerDisplay.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}
onTimerComplete() {
// タイマー終了処理
this.stopTimer();
this.stop(); // メトロノームを停止
// アラーム音を鳴らす(短く3回)
this.playAlarm();
}
playAlarm() {
const alarmTimes = [0, 0.15, 0.3]; // 3回のアラーム音
alarmTimes.forEach(offset => {
setTimeout(() => {
const osc = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
osc.connect(gainNode);
gainNode.connect(this.audioContext.destination);
// アラーム音: 高めの周波数で目立つように
osc.frequency.value = 1200;
osc.type = 'sine';
gainNode.gain.value = this.volume * 1.2;
const now = this.audioContext.currentTime;
gainNode.gain.setValueAtTime(gainNode.gain.value, now);
gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.1);
osc.start(now);
osc.stop(now + 0.1);
}, offset * 1000);
});
}
// イベントリスナー初期化
initEventListeners() {
// 再生/停止ボタン
document.getElementById('playBtn').addEventListener('click', () => {
this.toggle();
});
// タップテンポボタン
document.getElementById('tapBtn').addEventListener('click', () => {
this.handleTap();
});
// テンポスライダー
document.getElementById('tempoSlider').addEventListener('input', (e) => {
this.setTempo(parseInt(e.target.value));
});
// テンポ入力(小数点対応)
document.getElementById('tempoInput').addEventListener('input', (e) => {
this.setTempo(parseFloat(e.target.value));
});
// 拍子選択
document.getElementById('beatsPerBar').addEventListener('change', (e) => {
this.setBeatsPerBar(e.target.value);
});
// リズムパターン
document.getElementById('rhythmPattern').addEventListener('change', (e) => {
this.setRhythmPattern(e.target.value);
});
// 音色選択
document.getElementById('soundType').addEventListener('change', (e) => {
this.setSoundType(e.target.value);
});
// 音量スライダー
document.getElementById('volumeSlider').addEventListener('input', (e) => {
this.setVolume(parseInt(e.target.value));
});
// アニメーション選択
document.getElementById('animationType').addEventListener('change', (e) => {
this.setAnimationType(e.target.value);
});
// 弱拍音オプション
document.getElementById('subdivisionSound').addEventListener('change', (e) => {
this.subdivisionSound = e.target.checked;
this.toggleSubdivisionVolumeControl();
this.saveSettings();
});
// 細分化拍音量スライダー
document.getElementById('subdivisionVolumeSlider').addEventListener('input', (e) => {
this.setSubdivisionVolume(parseInt(e.target.value));
});
// プリセットボタン
document.querySelectorAll('.btn-preset').forEach(btn => {
btn.addEventListener('click', (e) => {
const bpm = parseInt(e.target.dataset.bpm);
this.setTempo(bpm);
});
});
// リセットボタン
document.getElementById('resetBtn').addEventListener('click', () => {
const lang = localStorage.getItem('language') || 'ja';
if (confirm(lang === 'ja'
? '設定を初期状態にリセットしますか?'
: 'Reset all settings to default?')) {
this.resetSettings();
}
});
// プリセット保存ボタン
document.getElementById('savePresetBtn').addEventListener('click', () => {
this.saveCurrentAsPreset();
});
// タイマー設定
document.getElementById('timerMinutes').addEventListener('input', (e) => {
this.timerMinutes = Math.max(0, parseInt(e.target.value) || 0);
this.updateTimerPreview();
});
document.getElementById('timerSeconds').addEventListener('input', (e) => {
let seconds = Math.max(0, Math.min(59, parseInt(e.target.value) || 0));
e.target.value = seconds;
this.timerSeconds = seconds;
this.updateTimerPreview();
});
document.getElementById('timerEnabled').addEventListener('change', (e) => {
this.timerEnabled = e.target.checked;
this.updateTimerPreview();
});
// キーボードショートカット
document.addEventListener('keydown', (e) => {
// スペースキー: 再生/停止
if (e.code === 'Space') {
e.preventDefault();
this.toggle();
}
// 上矢印: テンポ+1 (Shift押下時は+10)
if (e.code === 'ArrowUp') {
e.preventDefault();
const step = e.shiftKey ? 10 : 1;
this.setTempo(this.tempo + step);
}
// 下矢印: テンポ-1 (Shift押下時は-10)
if (e.code === 'ArrowDown') {
e.preventDefault();
const step = e.shiftKey ? 10 : 1;
this.setTempo(this.tempo - step);
}
// Tキー: タップテンポ
if (e.code === 'KeyT') {
e.preventDefault();
this.handleTap();
}
});
}
// タイマープレビューを更新
updateTimerPreview() {
const timerDisplay = document.getElementById('timerDisplayHeader');
if (this.timerEnabled) {
const totalSeconds = this.timerMinutes * 60 + this.timerSeconds;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
timerDisplay.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
} else {
timerDisplay.textContent = '--:--';
}
}
// カスタムプリセット管理
loadCustomPresets() {
const saved = localStorage.getItem('customPresets');
return saved ? JSON.parse(saved) : [];
}
saveCustomPresets() {
localStorage.setItem('customPresets', JSON.stringify(this.customPresets));
}
saveCurrentAsPreset() {
const lang = localStorage.getItem('language') || 'ja';
const name = prompt(lang === 'ja'
? 'プリセット名を入力してください:'
: 'Enter preset name:');
if (!name || name.trim() === '') return;
const preset = {
id: Date.now(),
name: name.trim(),
tempo: this.tempo,
beatsPerBar: this.beatsPerBar,
rhythmPattern: this.rhythmPattern
};
this.customPresets.push(preset);
this.saveCustomPresets();
this.renderPresetsList();
}
loadPreset(presetId) {
const preset = this.customPresets.find(p => p.id === presetId);
if (!preset) return;
this.setTempo(preset.tempo);
this.setBeatsPerBar(preset.beatsPerBar);
this.setRhythmPattern(preset.rhythmPattern);
// UIを更新
document.getElementById('beatsPerBar').value = preset.beatsPerBar;
document.getElementById('rhythmPattern').value = preset.rhythmPattern;
this.activePresetId = presetId;
this.renderPresetsList();
}
deletePreset(presetId) {
const preset = this.customPresets.find(p => p.id === presetId);
if (!preset) return;
const lang = localStorage.getItem('language') || 'ja';
const confirmMsg = lang === 'ja'
? `「${preset.name}」を削除しますか?`
: `Delete "${preset.name}"?`;
if (!confirm(confirmMsg)) return;
this.customPresets = this.customPresets.filter(p => p.id !== presetId);
if (this.activePresetId === presetId) {
this.activePresetId = null;
}
this.saveCustomPresets();
this.renderPresetsList();
}
getRhythmPatternName(pattern) {
const lang = localStorage.getItem('language') || 'ja';
const translationsMap = {
ja: {
simple: '4分音符',
eighth: '8分音符',
triplet: '3連符',
sixteenth: '16分音符',
sextuplet: '6連符'
},
en: {
simple: 'Quarter Notes',
eighth: 'Eighth Notes',
triplet: 'Triplets',
sixteenth: 'Sixteenth Notes',
sextuplet: 'Sextuplets'
}
};
return translationsMap[lang][pattern] || pattern;
}
renderPresetsList() {
const container = document.getElementById('savedPresetsList');
container.innerHTML = '';
if (this.customPresets.length === 0) {
const lang = localStorage.getItem('language') || 'ja';
const empty = document.createElement('div');
empty.style.color = '#888';
empty.style.textAlign = 'center';
empty.style.padding = '20px 0';
empty.style.fontSize = '0.9rem';
empty.textContent = lang === 'ja'
? '保存されたプリセットはありません'
: 'No saved presets';
container.appendChild(empty);
return;
}
this.customPresets.forEach(preset => {
const item = document.createElement('div');
item.className = 'preset-item';
if (preset.id === this.activePresetId) {
item.classList.add('active');
}
const header = document.createElement('div');
header.className = 'preset-item-header';
const name = document.createElement('div');
name.className = 'preset-name';
name.textContent = preset.name;
const deleteBtn = document.createElement('button');
deleteBtn.className = 'preset-delete-btn';
deleteBtn.textContent = '×';
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.deletePreset(preset.id);
});
header.appendChild(name);
header.appendChild(deleteBtn);
const info = document.createElement('div');
info.className = 'preset-info';
const tempoRow = document.createElement('div');
tempoRow.className = 'preset-info-row';
tempoRow.innerHTML = `
<span class="preset-info-label">Tempo:</span>
<span class="preset-info-value">${preset.tempo} BPM</span>
`;
const lang = localStorage.getItem('language') || 'ja';
const beatRow = document.createElement('div');
beatRow.className = 'preset-info-row';
beatRow.innerHTML = `
<span class="preset-info-label">${lang === 'ja' ? '拍子:' : 'Beats:'}</span>
<span class="preset-info-value">${preset.beatsPerBar}/4</span>
`;
const rhythmRow = document.createElement('div');
rhythmRow.className = 'preset-info-row';
rhythmRow.innerHTML = `
<span class="preset-info-label">${lang === 'ja' ? 'リズム:' : 'Rhythm:'}</span>
<span class="preset-info-value">${this.getRhythmPatternName(preset.rhythmPattern)}</span>
`;
info.appendChild(tempoRow);
info.appendChild(beatRow);
info.appendChild(rhythmRow);
item.appendChild(header);
item.appendChild(info);
// アイテムクリックでロード
item.addEventListener('click', () => {
this.loadPreset(preset.id);
});
container.appendChild(item);
});
}
}
// テーマ切り替え機能
class ThemeManager {
constructor() {
this.currentTheme = localStorage.getItem('theme') || 'dark';
this.themeToggle = document.getElementById('themeToggle');
this.init();
}
init() {
// 保存されたテーマを適用
this.applyTheme(this.currentTheme);
// チェックボックスの変更イベント
this.themeToggle.addEventListener('change', () => {
this.toggleTheme();
});
}
applyTheme(theme) {
if (theme === 'light') {
document.body.classList.add('light-mode');
this.themeToggle.checked = true;
} else {
document.body.classList.remove('light-mode');
this.themeToggle.checked = false;
}
this.currentTheme = theme;
}
toggleTheme() {
const newTheme = this.currentTheme === 'dark' ? 'light' : 'dark';
this.applyTheme(newTheme);
localStorage.setItem('theme', newTheme);
}
}
// 言語管理クラス
class LanguageManager {
constructor() {
this.currentLang = localStorage.getItem('language') || 'ja';
this.langToggle = document.getElementById('langToggle');
// 翻訳辞書
this.translations = {
ja: {
title: 'Metronome',
start: 'スタート',
tapTempo: 'タップテンポ',
tempo: 'テンポ',
timeSignature: '拍子',
beats1: '1拍',
beats2: '2拍',
beats3: '3拍',
beats4: '4拍',
beats5: '5拍',
beats6: '6拍',
beats7: '7拍',
beats8: '8拍',
rhythm: 'リズムパターン',
simple: '4分音符',
eighth: '8分音符',
triplet: '3連符',
sixteenth: '16分音符',
sextuplet: '6連符',
sound: '音色',
soundClick: 'クリック',
soundBeep: 'ビープ',
soundWood: 'ウッド',
soundCowbell: 'カウベル',
volume: '音量',
animation: 'アニメーション',
pendulum: '振り子',
pulse: 'パルス',
flash: '点滅',
none: 'なし',
presets: 'プリセット',
shortcuts: 'キーボードショートカット',
shortcutPlay: '再生/停止',
shortcutTempo: 'テンポ ±1 (Shift押下で ±10)',
shortcutTap: 'タップテンポ',
reset: '設定をリセット',
subdivisionSound: '細分化拍で別の音を使用',
subdivisionVolume: '細分化拍の音量',
timer: 'タイマー',
minutes: '分',
seconds: '秒',
timerEnabled: 'タイマーを有効にする',
savedPresets: 'プリセット',
savePreset: '+ 保存',
musicAnalysis: '音楽解析',
uploadMusic: '音楽をアップロード',
uploadHint: 'クリックまたはドラッグ&ドロップ',
fileName: 'ファイル',
detectedBPM: '検出BPM',
playMusic: '▶ 再生',
stopMusic: '■ 停止',
removeMusic: '× 削除',
syncWithMetronome: 'メトロノームと同期',
analyzing: '解析中...',
musicVolume: '曲の音量'
},
en: {
title: 'Metronome',
start: 'Start',
tapTempo: 'Tap Tempo',
tempo: 'Tempo',
timeSignature: 'Time Signature',
beats1: '1 beat',
beats2: '2 beats',
beats3: '3 beats',
beats4: '4 beats',