포트폴리오

개인 포트폴리오 사이트입니다

201601019

바이브코딩 2026. 10. 19.

 

매장 안내 방송
(AnnouncePlayer) 

WinForms로 제작된 알파버전이므로, 추가 지원 및 업데이트를 하지 않습니다.

 

Announce Player.z01
19.53MB
Announce Player.z02
19.53MB
Announce Player.zip
6.33MB

 

 

이 프로그램은 클로드(Haiku 5.5)에서 바이브 코딩으로  **C#**으로 작성되었습니다.

  • 언어: C# (.NET 10)
  • UI 프레임워크: WinForms (Windows 데스크톱 화면)
  • 오디오 라이브러리: NAudio (MP3/WAV 재생, Windows 오디오 세션 볼륨 제어)
  • 음성 생성: System.Speech (Windows 내장 TTS)
  • 데이터 저장: System.Text.Json (예약, 플레이리스트 등을 JSON 파일로 저장)
  • 자동 시작: Windows 레지스트리(Registry) 사용

 

소스코드

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
using NAudio.CoreAudioApi;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using Microsoft.Win32;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
 
public class Schedule
{
    public string Time { get; set; } = "";
    public List<string> Mp3Paths { get; set; } = new();
    public string? LastRunDate { get; set; }
}
 
public class AppSettings
{
    public double FadeInSeconds { get; set; } = 0;
    public double FadeOutSeconds { get; set; } = 0;
}
 
public class MainForm : Form
{
    // ---------- 색상 ----------
    private static readonly Color AccentTeal = Color.FromArgb(0, 168, 180);
    private static readonly Color PanelBg = Color.FromArgb(246, 248, 249);
    private static readonly Color TextDark = Color.FromArgb(40, 44, 52);
    private static readonly Color TextSub = Color.FromArgb(130, 136, 146);
    private static readonly Color StatusOnAir = Color.FromArgb(110, 255, 150);
    private static readonly Color StatusIdle = Color.FromArgb(255, 110, 110);
    private static readonly Color HeaderText = Color.FromArgb(220, 250, 250);
 
    private const int TtsRate = -2;
    private const float TtsVolumeBoost = 2.0f;
 
    private const string AutoStartName = "AnnouncePlayer";
    private const string RunKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
 
    private const string FixedIconPath = @"C:\Users\kimun\AnnouncePlayer\icons\tray.ico";
 
    private static readonly string[] DefaultSamples =
    {
        "안녕하세요. 오늘도 저희 매장을 찾아주셔서 감사합니다.",
        "오늘 영업은 밤 10시에 종료됩니다. 이용에 참고해 주세요.",
        "고객님, 주차 차량 이동 안내 말씀드립니다.",
        "매장 내 음식물 반입은 삼가 주시기 바랍니다.",
        "잠시 후 점심 특선 메뉴 안내를 시작하겠습니다.",
        "방문해 주셔서 감사합니다. 안전하게 귀가하세요."
    };
 
    // ---------- 경로 ----------
    private readonly string _dataPath = Path.Combine(AppContext.BaseDirectory, "schedules.json");
    private readonly string _playlistPath = Path.Combine(AppContext.BaseDirectory, "playlist.json");
    private readonly string _textsPath = Path.Combine(AppContext.BaseDirectory, "texts.json");
    private readonly string _samplesPath = Path.Combine(AppContext.BaseDirectory, "samples.json");
    private readonly string _settingsPath = Path.Combine(AppContext.BaseDirectory, "settings.json");
    private readonly string _ttsDir = Path.Combine(AppContext.BaseDirectory, "tts");
    private readonly string? _iconFile = FindIconFile();
    private readonly string? _chimePath = FindProjectFile(Path.Combine("effects", "chime.wav"));
 
    // ---------- 데이터 / 상태 ----------
    private readonly List<Schedule> _schedules = new();
    private readonly int _ownPid = Environment.ProcessId;
    private AppSettings _settings = new();
 
    private readonly System.Windows.Forms.Timer _tick = new() { Interval = 1000 };
    private readonly System.Windows.Forms.Timer _guard = new() { Interval = 300 };
    private readonly System.Windows.Forms.Timer _progress = new() { Interval = 500 };
    private readonly System.Windows.Forms.Timer _volumeView = new() { Interval = 500 };
    private readonly System.Windows.Forms.Timer _marquee = new() { Interval = 30 };
    private readonly System.Windows.Forms.Timer _fade = new() { Interval = 50 };
 
    private IWavePlayer? _player;
    private AudioFileReader? _reader;
    private bool _announcing;
    private readonly Dictionary<string, float> _savedVolumes = new();
 
    // 다른 프로그램 페이드 상태
    private float _fadeFrom = 1f;   // 0~1 (현재 시작 배율)
    private float _fadeTo = 1f;     // 0~1 (목표 배율)
    private DateTime _fadeStart;
    private double _fadeDuration;
    private bool _fadingOut;
 
    private Queue<string> _queue = new();
    private int _queueTotal;
    private int _queueIndex;
 
    private readonly List<string> _playlist = new();
    private readonly List<string> _ttsTexts = new();
    private readonly List<string> _samples = new();
 
    private bool _volumeLock;
    private int _lockedVolume = 50;
    private bool _updatingVolumeUi;
    private int _marqueeX;
 
    private readonly NotifyIcon _tray = new();
    private bool _realExit;
 
    // ---------- 헤더 (높이 110) ----------
    private readonly Panel _header = new()
    {
        Dock = DockStyle.Top,
        Height = 110,
        BackColor = AccentTeal
    };
 
    private readonly Label _lblTitle = new()
    {
        Text = "매장 안내 방송",
        ForeColor = Color.White,
        BackColor = AccentTeal,
        Font = new Font("맑은 고딕", 13F, FontStyle.Bold),
        AutoSize = true,
        Location = new Point(16, 10)
    };
 
    private readonly Label _lblStatus = new()
    {
        Text = "● 대기 중",
        ForeColor = StatusIdle,
        BackColor = AccentTeal,
        Font = new Font("맑은 고딕", 9F, FontStyle.Bold),
        AutoSize = true,
        Location = new Point(18, 42)
    };
 
    private readonly Panel _marqueeArea = new()
    {
        Location = new Point(16, 64),
        Size = new Size(270, 20),
        BackColor = AccentTeal
    };
 
    private readonly Label _lblNowPlaying = new()
    {
        Text = "",
        ForeColor = Color.White,
        BackColor = AccentTeal,
        Font = new Font("맑은 고딕", 9.5F, FontStyle.Bold),
        AutoSize = true,
        Location = new Point(0, 0)
    };
 
    private readonly Label _lblRemain = new()
    {
        Text = "",
        ForeColor = HeaderText,
        BackColor = AccentTeal,
        Font = new Font("맑은 고딕", 9F),
        AutoSize = true,
        Location = new Point(18, 88)
    };
 
    private readonly Label _lblVolumeTitle = new()
    {
        Text = "볼륨",
        ForeColor = HeaderText,
        BackColor = AccentTeal,
        Font = new Font("맑은 고딕", 9F),
        AutoSize = true,
        Location = new Point(330, 12)
    };
 
    private readonly TrackBar _tbVolume = new()
    {
        Location = new Point(360, 6),
        Size = new Size(140, 30),
        Minimum = 0,
        Maximum = 100,
        TickStyle = TickStyle.None,
        Value = 50
    };
 
    private readonly NumericUpDown _nudVolume = new()
    {
        Location = new Point(505, 10),
        Size = new Size(50, 24),
        Minimum = 0,
        Maximum = 100,
        Value = 50,
        Font = new Font("맑은 고딕", 9F)
    };
 
    private readonly Panel _lockPanel = new()
    {
        Location = new Point(420, 40),
        Size = new Size(150, 24),
        BackColor = AccentTeal
    };
 
    private readonly CheckBox _chkVolumeLock = new()
    {
        Text = "",
        AutoSize = false,
        Size = new Size(16, 16),
        Location = new Point(0, 4),
        BackColor = AccentTeal,
        Cursor = Cursors.Hand
    };
 
    private readonly Label _lblVolumeLock = new()
    {
        Text = "볼륨 고정",
        ForeColor = Color.White,
        BackColor = AccentTeal,
        Font = new Font("맑은 고딕", 9F),
        AutoSize = true,
        Location = new Point(22, 3),
        Cursor = Cursors.Hand
    };
 
    // ---------- 메인 탭 ----------
    private readonly TabControl _tabs = new()
    {
        Location = new Point(0, 110),
        Size = new Size(580, 380),
        Font = new Font("맑은 고딕", 10F)
    };
 
    private readonly TabPage _tabPlaylist = new("플레이리스트") { BackColor = PanelBg };
    private readonly TabPage _tabSchedule = new("예약 목록") { BackColor = PanelBg };
    private readonly TabPage _tabSettings = new("설정") { BackColor = PanelBg };
 
    // ---------- 플레이리스트 탭 ----------
    private readonly CheckedListBox _clbPlaylist = new()
    {
        Location = new Point(20, 12),
        Size = new Size(530, 120),
        BorderStyle = BorderStyle.None,
        BackColor = Color.White,
        ForeColor = TextDark,
        Font = new Font("맑은 고딕", 10F),
        IntegralHeight = false,
        CheckOnClick = true
    };
 
    private readonly Label _lblSummary = new()
    {
        AutoSize = false,
        TextAlign = ContentAlignment.MiddleLeft,
        Text = "곡을 추가해 주세요",
        ForeColor = TextSub,
        Font = new Font("맑은 고딕", 9F),
        Location = new Point(20, 136),
        Size = new Size(530, 20)
    };
 
    private readonly TabControl _subTabs = new()
    {
        Location = new Point(20, 160),
        Size = new Size(530, 110)
    };
 
    private readonly TabPage _subSong = new("곡 추가") { BackColor = PanelBg };
    private readonly TabPage _subTts = new("음성 추가") { BackColor = PanelBg };
 
    private readonly Button _btnAddSong = new();
 
    private readonly TextBox _txtTts = new()
    {
        Location = new Point(10, 8),
        Size = new Size(400, 40),
        Multiline = true,
        ScrollBars = ScrollBars.Vertical,
        WordWrap = true,
        Font = new Font("맑은 고딕", 10F)
    };
 
    private readonly Button _btnTtsAdd = new();
 
    private readonly ComboBox _cbSample = new();
    private readonly Button _btnSampleAdd = new();
    private readonly Button _btnSampleEdit = new();
    private readonly Button _btnSampleDel = new();
 
    private readonly ListBox _lbTtsHistory = new();
 
    private readonly Button _btnRemoveSong = new();
    private readonly Button _btnClear = new();
 
    private readonly ComboBox _cbAmPm = new();
    private readonly ComboBox _cbHour12 = new();
    private readonly ComboBox _cbMinute = new();
 
    private readonly Label _lblColon = new()
    {
        Text = ":",
        AutoSize = true,
        Font = new Font("맑은 고딕", 10F, FontStyle.Bold),
        ForeColor = TextDark
    };
 
    private readonly Button _btnAddSchedule = new();
    private readonly Button _btnTest = new();
    private readonly Button _btnStop = new();
 
    // ---------- 예약 목록 탭 ----------
    private readonly ListView _lv = new()
    {
        Location = new Point(20, 12),
        Size = new Size(530, 190),
        View = View.Details,
        FullRowSelect = true,
        CheckBoxes = true,
        MultiSelect = false,
        BorderStyle = BorderStyle.None,
        BackColor = Color.White,
        ForeColor = TextDark,
        Font = new Font("맑은 고딕", 9.5F)
    };
 
    private readonly Button _btnRemoveSchedule = new();
    private readonly Button _btnClearSchedule = new();
 
    private readonly Label _lblEditTitle = new()
    {
        Text = "선택한 예약 시간 수정:",
        AutoSize = true,
        Font = new Font("맑은 고딕", 9F, FontStyle.Bold),
        ForeColor = TextDark,
        Location = new Point(20, 256)
    };
 
    private readonly ComboBox _cbEditAmPm = new();
    private readonly ComboBox _cbEditHour12 = new();
    private readonly ComboBox _cbEditMinute = new();
 
    private readonly Label _lblEditColon = new()
    {
        Text = ":",
        AutoSize = true,
        Font = new Font("맑은 고딕", 10F, FontStyle.Bold),
        ForeColor = TextDark
    };
 
    private readonly Button _btnTimeEdit = new();
 
    // ---------- 설정 탭 ----------
    private readonly CheckBox _chkAutoStart = new()
    {
        Text = "윈도우 시작 시 자동으로 실행",
        AutoSize = true,
        Font = new Font("맑은 고딕", 10F),
        ForeColor = TextDark,
        Location = new Point(20, 20)
    };
 
    private readonly Label _lblSettingsInfo = new()
    {
        Text = "체크하면 Windows에 로그인할 때 이 프로그램이 자동으로 실행됩니다.",
        AutoSize = true,
        Font = new Font("맑은 고딕", 9F),
        ForeColor = TextSub,
        Location = new Point(20, 56)
    };
 
    private readonly Label _lblFadeIn = new()
    {
        Text = "Fade In (초):",
        AutoSize = true,
        Font = new Font("맑은 고딕", 10F),
        ForeColor = TextDark,
        Location = new Point(20, 100)
    };
 
    private readonly NumericUpDown _nudFadeIn = new()
    {
        Location = new Point(140, 97),
        Size = new Size(70, 26),
        Minimum = 0,
        Maximum = 30,
        DecimalPlaces = 1,
        Increment = 0.5M,
        Font = new Font("맑은 고딕", 10F)
    };
 
    private readonly Label _lblFadeOut = new()
    {
        Text = "Fade Out (초):",
        AutoSize = true,
        Font = new Font("맑은 고딕", 10F),
        ForeColor = TextDark,
        Location = new Point(20, 140)
    };
 
    private readonly NumericUpDown _nudFadeOut = new()
    {
        Location = new Point(140, 137),
        Size = new Size(70, 26),
        Minimum = 0,
        Maximum = 30,
        DecimalPlaces = 1,
        Increment = 0.5M,
        Font = new Font("맑은 고딕", 10F)
    };
 
    private readonly Label _lblFadeInfo = new()
    {
        Text = "방송 시작 시 다른 프로그램 소리를 Fade Out 시간 동안 줄이고,\n방송 종료 시 Fade In 시간 동안 원래 볼륨으로 되돌립니다. (0이면 즉시 적용)",
        AutoSize = true,
        Font = new Font("맑은 고딕", 9F),
        ForeColor = TextSub,
        Location = new Point(20, 180)
    };
 
    // ---------- 생성자 ----------
    public MainForm()
    {
        Text = "매장 안내 방송";
        ClientSize = new Size(580, 500);
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        StartPosition = FormStartPosition.CenterScreen;
        Font = new Font("맑은 고딕", 9F);
 
        Icon = LoadAppIcon();
 
        _marqueeArea.Controls.Add(_lblNowPlaying);
 
        // 하위 탭 1: 곡 추가 (버튼을 탭 가운데에 배치)
        _btnAddSong.Text = "곡 추가";
        _btnAddSong.Size = new Size(120, 36);
        _btnAddSong.FlatStyle = FlatStyle.Flat;
        _btnAddSong.Font = new Font("맑은 고딕", 9.5F);
        _btnAddSong.Cursor = Cursors.Hand;
        _btnAddSong.FlatAppearance.BorderSize = 0;
        _btnAddSong.BackColor = AccentTeal;
        _btnAddSong.ForeColor = Color.White;
        _btnAddSong.Click += (s, e) => AddSongs();
        _subSong.Controls.Add(_btnAddSong);
        _subSong.Resize += (s, e) => CenterButton(_btnAddSong, _subSong);
        CenterButton(_btnAddSong, _subSong);
 
        // 하위 탭 2: 음성 추가
        InitButton(_btnTtsAdd, "음성 추가", true, 420, 8, 90);
        _btnTtsAdd.Click += (s, e) => AddTtsSong();
 
        _cbSample.Location = new Point(10, 56);
        _cbSample.Size = new Size(230, 24);
        _cbSample.DropDownStyle = ComboBoxStyle.DropDownList;
        _cbSample.Font = new Font("맑은 고딕", 9F);
        _cbSample.SelectedIndexChanged += (s, e) =>
        {
            if (_cbSample.SelectedIndex >= 0)
            {
                _txtTts.Text = _samples[_cbSample.SelectedIndex];
                _txtTts.SelectionStart = _txtTts.Text.Length;
            }
        };
 
        InitButton(_btnSampleAdd, "예시 추가", false, 248, 55, 80);
        InitButton(_btnSampleEdit, "예시 수정", false, 334, 55, 80);
        InitButton(_btnSampleDel, "예시 삭제", false, 420, 55, 80);
        _btnSampleAdd.Click += (s, e) => SampleAdd();
        _btnSampleEdit.Click += (s, e) => SampleEdit();
        _btnSampleDel.Click += (s, e) => SampleDelete();
 
        _lbTtsHistory.Location = new Point(10, 84);
        _lbTtsHistory.Size = new Size(400, 0);
        _lbTtsHistory.Font = new Font("맑은 고딕", 9F);
        _lbTtsHistory.IntegralHeight = false;
        _lbTtsHistory.Visible = false;
        _lbTtsHistory.SelectedIndexChanged += (s, e) =>
        {
            if (_lbTtsHistory.SelectedIndex >= 0)
            {
                _txtTts.Text = _ttsTexts[_lbTtsHistory.SelectedIndex];
                _txtTts.SelectionStart = _txtTts.Text.Length;
                _txtTts.Focus();
            }
        };
 
        _subTts.Controls.AddRange(new Control[]
        {
            _txtTts, _btnTtsAdd,
            _cbSample, _btnSampleAdd, _btnSampleEdit, _btnSampleDel,
            _lbTtsHistory
        });
 
        _subTabs.TabPages.Add(_subSong);
        _subTabs.TabPages.Add(_subTts);
 
        InitButton(_btnRemoveSong, "체크 삭제", false, 20, 278, 80);
        InitButton(_btnClear, "전체 삭제", false, 106, 278, 80);
        _btnRemoveSong.Click += (s, e) => RemoveCheckedSongs();
        _btnClear.Click += (s, e) => ClearPlaylist();
 
        _cbAmPm.Location = new Point(20, 324);
        _cbAmPm.Width = 70;
        _cbAmPm.DropDownStyle = ComboBoxStyle.DropDownList;
        _cbAmPm.Font = new Font("맑은 고딕", 10F);
        _cbAmPm.Items.AddRange(new object[] { "오전", "오후" });
        _cbAmPm.SelectedIndex = 0;
 
        InitHour12(_cbHour12, 98, 324);
        InitMinute(_cbMinute, 170, 324);
        _lblColon.Location = new Point(162, 327);
 
        InitButton(_btnAddSchedule, "예약 추가", true, 240, 320, 80);
        InitButton(_btnTest, "지금 재생", true, 326, 320, 80);
        InitButton(_btnStop, "방송 정지", false, 412, 320, 80);
 
        _btnAddSchedule.Click += (s, e) => AddSchedule();
        _btnTest.Click += (s, e) => PlayList(GetCheckedSongs(), force: true);
        _btnStop.Click += (s, e) => FinishPlayback();
 
        _tabPlaylist.Controls.AddRange(new Control[]
        {
            _clbPlaylist, _lblSummary, _subTabs,
            _btnRemoveSong, _btnClear,
            _cbAmPm, _cbHour12, _lblColon, _cbMinute,
            _btnAddSchedule, _btnTest, _btnStop
        });
 
        // 예약 목록 탭
        _lv.Columns.Add("시간", 110);
        _lv.Columns.Add("곡 목록", 410);
        _lv.SelectedIndexChanged += (s, e) => LoadSelectedTimeToEditor();
        _lv.MouseUp += (s, e) => LoadSelectedTimeToEditor();
        _lv.ItemCheck += (s, e) => BeginInvoke(new Action(LoadSelectedTimeToEditor));
 
        InitButton(_btnRemoveSchedule, "체크 삭제", false, 20, 210, 80);
        InitButton(_btnClearSchedule, "전체 삭제", false, 106, 210, 80);
        _btnRemoveSchedule.Click += (s, e) => RemoveCheckedSchedules();
        _btnClearSchedule.Click += (s, e) => ClearSchedules();
 
        _cbEditAmPm.Location = new Point(20, 280);
        _cbEditAmPm.Width = 70;
        _cbEditAmPm.DropDownStyle = ComboBoxStyle.DropDownList;
        _cbEditAmPm.Font = new Font("맑은 고딕", 10F);
        _cbEditAmPm.Items.AddRange(new object[] { "오전", "오후" });
        _cbEditAmPm.SelectedIndex = 0;
 
        InitHour12(_cbEditHour12, 98, 280);
        InitMinute(_cbEditMinute, 170, 280);
        _lblEditColon.Location = new Point(162, 283);
 
        InitButton(_btnTimeEdit, "시간 수정", true, 240, 276, 80);
        _btnTimeEdit.Click += (s, e) => ChangeScheduleTime();
 
        _tabSchedule.Controls.AddRange(new Control[]
        {
            _lv, _btnRemoveSchedule, _btnClearSchedule,
            _lblEditTitle, _cbEditAmPm, _cbEditHour12, _lblEditColon, _cbEditMinute,
            _btnTimeEdit
        });
 
        // 설정 탭
        _chkAutoStart.CheckedChanged += (s, e) => SetAutoStart(_chkAutoStart.Checked);
        _nudFadeIn.ValueChanged += (s, e) => SaveSettings();
        _nudFadeOut.ValueChanged += (s, e) => SaveSettings();
        _tabSettings.Controls.AddRange(new Control[]
        {
            _chkAutoStart, _lblSettingsInfo,
            _lblFadeIn, _nudFadeIn, _lblFadeOut, _nudFadeOut, _lblFadeInfo
        });
 
        _tabs.TabPages.Add(_tabPlaylist);
        _tabs.TabPages.Add(_tabSchedule);
        _tabs.TabPages.Add(_tabSettings);
 
        _tbVolume.Scroll += (s, e) => OnVolumeUiChanged(_tbVolume.Value);
        _nudVolume.ValueChanged += (s, e) => OnVolumeUiChanged((int)_nudVolume.Value);
        _chkVolumeLock.CheckedChanged += (s, e) => OnVolumeLockChanged();
        _lblVolumeLock.Click += (s, e) => _chkVolumeLock.Checked = !_chkVolumeLock.Checked;
 
        _lockPanel.Controls.Add(_chkVolumeLock);
        _lockPanel.Controls.Add(_lblVolumeLock);
 
        _header.Controls.Add(_lockPanel);
        _header.Controls.AddRange(new Control[]
        {
            _lblTitle, _lblStatus, _marqueeArea, _lblRemain,
            _lblVolumeTitle, _tbVolume, _nudVolume
        });
        _lockPanel.BringToFront();
 
        Controls.Add(_tabs);
        Controls.Add(_header);
 
        SetupTray();
 
        _tick.Tick += (s, e) => CheckSchedules();
        _guard.Tick += (s, e) => MuteOthers();
        _progress.Tick += (s, e) => UpdateProgress();
        _volumeView.Tick += (s, e) => SyncVolumeFromSystem();
        _marquee.Tick += (s, e) => MoveMarquee();
        _fade.Tick += (s, e) => StepFade();
        Load += (s, e) =>
        {
            LoadSettings();
            LoadPlaylist();
            LoadTtsTexts();
            LoadSamples();
            LoadSchedules();
            RefreshList();
            RefreshPlaylistView();
            RefreshTtsHistory();
            RefreshSampleList();
            LoadAutoStartState();
            SyncVolumeFromSystem();
            _tick.Start();
            _volumeView.Start();
            _marquee.Start();
        };
        FormClosing += (s, e) =>
        {
            if (_realExit)
            {
                _tick.Stop();
                _guard.Stop();
                _progress.Stop();
                _volumeView.Stop();
                _marquee.Stop();
                _fade.Stop();
                FinishPlayback();
                _tray.Visible = false;
            }
        };
        Resize += (s, e) =>
        {
            if (WindowState == FormWindowState.Minimized)
                HideToTray();
        };
    }
 
    // ---------- 버튼을 탭 페이지 가운데에 배치 ----------
    private static void CenterButton(Button btn, Control parent)
    {
        int x = (parent.ClientSize.Width - btn.Width) / 2;
        int y = (parent.ClientSize.Height - btn.Height) / 2;
        btn.Location = new Point(Math.Max(0, x), Math.Max(0, y));
    }
 
    // ---------- 설정 저장/불러오기 ----------
    private void LoadSettings()
    {
        if (File.Exists(_settingsPath))
        {
            var loaded = JsonSerializer.Deserialize<AppSettings>(File.ReadAllText(_settingsPath));
            if (loaded != null) _settings = loaded;
        }
        _nudFadeIn.Value = (decimal)Math.Clamp(_settings.FadeInSeconds, 0, 30);
        _nudFadeOut.Value = (decimal)Math.Clamp(_settings.FadeOutSeconds, 0, 30);
    }
 
    private void SaveSettings()
    {
        _settings.FadeInSeconds = (double)_nudFadeIn.Value;
        _settings.FadeOutSeconds = (double)_nudFadeOut.Value;
        File.WriteAllText(_settingsPath, JsonSerializer.Serialize(_settings));
    }
 
    // ---------- 파일 찾기 ----------
    private static string? FindIconFile()
    {
        if (File.Exists(FixedIconPath)) return FixedIconPath;
 
        string rel = Path.Combine("icons", "tray.ico");
        string? found = FindProjectFile(rel);
        if (found != null) return found;
 
        string cwdCandidate = Path.Combine(Directory.GetCurrentDirectory(), rel);
        if (File.Exists(cwdCandidate)) return cwdCandidate;
 
        return null;
    }
 
    private static string? FindProjectFile(string relativePath)
    {
        var dir = new DirectoryInfo(AppContext.BaseDirectory);
        while (dir != null)
        {
            string candidate = Path.Combine(dir.FullName, relativePath);
            if (File.Exists(candidate)) return candidate;
            dir = dir.Parent;
        }
        return null;
    }
 
    private Icon LoadAppIcon()
    {
        if (_iconFile == null)
        {
            MessageBox.Show("tray.ico를 찾지 못했습니다.\n기본 아이콘으로 실행합니다.");
            return SystemIcons.Application;
        }
        try
        {
            return new Icon(_iconFile);
        }
        catch (Exception ex)
        {
            MessageBox.Show("아이콘 로딩 실패: " + ex.Message);
            return SystemIcons.Application;
        }
    }
 
    // ---------- 트레이 ----------
    private void SetupTray()
    {
        _tray.Icon = Icon ?? SystemIcons.Application;
        _tray.Text = "매장 안내 방송";
        _tray.Visible = false;
 
        var menu = new ContextMenuStrip();
        menu.Items.Add("열기", null, (s, e) => ShowFromTray());
        menu.Items.Add("종료", null, (s, e) => ExitApp());
        _tray.ContextMenuStrip = menu;
 
        _tray.DoubleClick += (s, e) => ShowFromTray();
    }
 
    private void HideToTray()
    {
        Hide();
        _tray.Icon = Icon ?? SystemIcons.Application;
        _tray.Visible = true;
        _tray.ShowBalloonTip(1500, "매장 안내 방송", "트레이에서 실행 중입니다.", ToolTipIcon.None);
    }
 
    private void ShowFromTray()
    {
        Show();
        WindowState = FormWindowState.Normal;
        _tray.Visible = false;
        Activate();
    }
 
    private void ExitApp()
    {
        _realExit = true;
        Close();
    }
 
    private void MoveMarquee()
    {
        int textWidth = _lblNowPlaying.PreferredWidth;
        int areaWidth = _marqueeArea.ClientSize.Width;
 
        if (textWidth <= areaWidth)
        {
            _lblNowPlaying.Location = new Point(0, 0);
            _marqueeX = areaWidth;
            return;
        }
 
        _marqueeX -= 1;
        if (_marqueeX < -textWidth) _marqueeX = areaWidth;
        _lblNowPlaying.Location = new Point(_marqueeX, 0);
    }
 
    // ---------- 시스템 볼륨 ----------
    private static MMDevice? GetDefaultDevice()
    {
        try
        {
            var enumerator = new MMDeviceEnumerator();
            return enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
        }
        catch
        {
            return null;
        }
    }
 
    private void SyncVolumeFromSystem()
    {
        using var device = GetDefaultDevice();
        if (device == null) return;
 
        if (_volumeLock)
        {
            int cur = (int)Math.Round(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
            if (cur != _lockedVolume)
                device.AudioEndpointVolume.MasterVolumeLevelScalar = _lockedVolume / 100f;
            if (device.AudioEndpointVolume.Mute)
                device.AudioEndpointVolume.Mute = false;
            return;
        }
 
        int percent = (int)Math.Round(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
        SetVolumeUi(percent);
    }
 
    private void SetVolumeUi(int percent)
    {
        _updatingVolumeUi = true;
        try
        {
            percent = Math.Clamp(percent, 0, 100);
            if (_tbVolume.Value != percent) _tbVolume.Value = percent;
            if (_nudVolume.Value != percent) _nudVolume.Value = percent;
        }
        finally
        {
            _updatingVolumeUi = false;
        }
    }
 
    private void OnVolumeUiChanged(int percent)
    {
        if (_updatingVolumeUi) return;
 
        if (_volumeLock)
        {
            SetVolumeUi(_lockedVolume);
            return;
        }
 
        percent = Math.Clamp(percent, 0, 100);
        SetVolumeUi(percent);
        ApplySystemVolume(percent);
    }
 
    private static void ApplySystemVolume(int percent)
    {
        using var device = GetDefaultDevice();
        if (device == null) return;
        device.AudioEndpointVolume.Mute = false;
        device.AudioEndpointVolume.MasterVolumeLevelScalar = percent / 100f;
    }
 
    private void OnVolumeLockChanged()
    {
        _volumeLock = _chkVolumeLock.Checked;
        _tbVolume.Enabled = !_volumeLock;
        _nudVolume.Enabled = !_volumeLock;
 
        if (_volumeLock)
        {
            _lockedVolume = (int)_nudVolume.Value;
            ApplySystemVolume(_lockedVolume);
        }
    }
 
    private void SetStatus(bool onAir)
    {
        _lblStatus.Text = onAir ? "● 방송 중" : "● 대기 중";
        _lblStatus.ForeColor = onAir ? StatusOnAir : StatusIdle;
    }
 
    // ---------- 자동 시작 ----------
    private void LoadAutoStartState()
    {
        using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath, false);
        bool enabled = key?.GetValue(AutoStartName) != null;
 
        _chkAutoStart.CheckedChanged -= (s, e) => SetAutoStart(_chkAutoStart.Checked);
        _chkAutoStart.Checked = enabled;
        _chkAutoStart.CheckedChanged += (s, e) => SetAutoStart(_chkAutoStart.Checked);
    }
 
    private void SetAutoStart(bool enable)
    {
        try
        {
            using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath, true)
                            ?? Registry.CurrentUser.CreateSubKey(RunKeyPath);
 
            if (enable)
            {
                string exePath = Environment.ProcessPath
                                 ?? Path.Combine(AppContext.BaseDirectory, "AnnouncePlayer.exe");
                key.SetValue(AutoStartName, $"\"{exePath}\"");
            }
            else
            {
                key.DeleteValue(AutoStartName, throwOnMissingValue: false);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("자동 시작 설정을 변경하지 못했습니다.\n" + ex.Message);
            LoadAutoStartState();
        }
    }
 
    // ---------- 숫자 → 한글 수사 변환 ----------
    private static string ToKoreanNumbers(string text)
        => Regex.Replace(text, @"\d+", m => NumberToKorean(m.Value));
 
    private static string NumberToKorean(string digits)
    {
        if (!long.TryParse(digits, out long n)) return digits;
        if (n == 0) return "영";
 
        string[] digit = { "", "일", "이", "삼", "사", "오", "육", "칠", "팔", "구" };
        string[] unit = { "", "십", "백", "천" };
        string[] bigUnit = { "", "만", "억", "조" };
 
        var sb = new StringBuilder();
        int bigIndex = 0;
 
        while (n > 0)
        {
            long chunk = n % 10000;
            n /= 10000;
 
            if (chunk > 0)
            {
                var part = new StringBuilder();
                for (int i = 0; i < 4; i++)
                {
                    int d = (int)(chunk % 10);
                    chunk /= 10;
                    if (d == 0) continue;
                    string num = (d == 1 && i > 0) ? "" : digit[d];
                    part.Insert(0, num + unit[i]);
                }
                sb.Insert(0, part.ToString() + bigUnit[bigIndex]);
            }
            bigIndex++;
        }
        return sb.ToString();
    }
 
    // ---------- 컨트롤 초기화 ----------
    private static void InitHour12(ComboBox cb, int x, int y)
    {
        cb.Location = new Point(x, y);
        cb.Width = 60;
        cb.DropDownStyle = ComboBoxStyle.DropDownList;
        cb.Font = new Font("맑은 고딕", 10F);
        for (int h = 1; h <= 12; h++)
            cb.Items.Add(h.ToString("D2"));
        cb.SelectedIndex = 0;
    }
 
    private static void InitMinute(ComboBox cb, int x, int y)
    {
        cb.Location = new Point(x, y);
        cb.Width = 60;
        cb.DropDownStyle = ComboBoxStyle.DropDownList;
        cb.Font = new Font("맑은 고딕", 10F);
        for (int m = 0; m <= 59; m++)
            cb.Items.Add(m.ToString("D2"));
        cb.SelectedIndex = 0;
    }
 
    private static void InitButton(Button b, string text, bool primary, int x, int y, int width)
    {
        b.Text = text;
        b.Location = new Point(x, y);
        b.Size = new Size(width, 30);
        b.FlatStyle = FlatStyle.Flat;
        b.Font = new Font("맑은 고딕", 8.5F);
        b.Cursor = Cursors.Hand;
        b.FlatAppearance.BorderSize = 0;
        b.BackColor = primary ? AccentTeal : Color.White;
        b.ForeColor = primary ? Color.White : TextDark;
    }
 
    // ---------- 예시 문구 관리 ----------
    private void SaveSamples()
        => File.WriteAllText(_samplesPath, JsonSerializer.Serialize(_samples));
 
    private void LoadSamples()
    {
        if (File.Exists(_samplesPath))
        {
            var loaded = JsonSerializer.Deserialize<List<string>>(File.ReadAllText(_samplesPath));
            if (loaded != null) _samples.AddRange(loaded);
        }
        else
        {
            _samples.AddRange(DefaultSamples);
            SaveSamples();
        }
    }
 
    private void RefreshSampleList()
    {
        int prev = _cbSample.SelectedIndex;
        _cbSample.BeginUpdate();
        _cbSample.Items.Clear();
        foreach (var s in _samples)
            _cbSample.Items.Add(s);
        _cbSample.EndUpdate();
        if (prev >= 0 && prev < _cbSample.Items.Count)
            _cbSample.SelectedIndex = prev;
    }
 
    private void SampleAdd()
    {
        string text = _txtTts.Text.Trim();
        if (text.Length == 0)
        {
            MessageBox.Show("추가할 문구를 입력란에 적어 주세요.");
            return;
        }
        if (_samples.Contains(text))
        {
            MessageBox.Show("이미 같은 예시 문구가 있습니다.");
            return;
        }
        _samples.Add(text);
        SaveSamples();
        RefreshSampleList();
        _cbSample.SelectedIndex = _samples.Count - 1;
    }
 
    private void SampleEdit()
    {
        int idx = _cbSample.SelectedIndex;
        if (idx < 0)
        {
            MessageBox.Show("수정할 예시 문구를 선택해 주세요.");
            return;
        }
        string text = _txtTts.Text.Trim();
        if (text.Length == 0)
        {
            MessageBox.Show("입력란에 수정할 문구를 적어 주세요.");
            return;
        }
        _samples[idx] = text;
        SaveSamples();
        RefreshSampleList();
        _cbSample.SelectedIndex = idx;
    }
 
    private void SampleDelete()
    {
        int idx = _cbSample.SelectedIndex;
        if (idx < 0)
        {
            MessageBox.Show("삭제할 예시 문구를 선택해 주세요.");
            return;
        }
        if (MessageBox.Show("선택한 예시 문구를 삭제할까요?", "확인",
            MessageBoxButtons.YesNo) != DialogResult.Yes) return;
 
        _samples.RemoveAt(idx);
        SaveSamples();
        RefreshSampleList();
        _cbSample.SelectedIndex = -1;
    }
 
    // ---------- 음성 문구 목록 ----------
    private void SaveTtsTexts()
        => File.WriteAllText(_textsPath, JsonSerializer.Serialize(_ttsTexts));
 
    private void LoadTtsTexts()
    {
        if (!File.Exists(_textsPath)) return;
        var loaded = JsonSerializer.Deserialize<List<string>>(File.ReadAllText(_textsPath));
        if (loaded != null) _ttsTexts.AddRange(loaded);
    }
 
    private void RefreshTtsHistory()
    {
        _lbTtsHistory.BeginUpdate();
        _lbTtsHistory.Items.Clear();
        foreach (var t in _ttsTexts)
            _lbTtsHistory.Items.Add(t);
        _lbTtsHistory.EndUpdate();
    }
 
    // ---------- TTS (효과음 + 음성 → WAV) ----------
    private void AddTtsSong()
    {
        string text = _txtTts.Text.Trim();
        if (text.Length == 0)
        {
            MessageBox.Show("안내 문구를 입력해 주세요.");
            return;
        }
 
        try
        {
            Directory.CreateDirectory(_ttsDir);
            string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            string speechPath = Path.Combine(_ttsDir, $"speech_{stamp}.wav");
            string outPath = Path.Combine(_ttsDir, $"tts_{stamp}.wav");
 
            using (var synth = new SpeechSynthesizer())
            {
                synth.SelectVoiceByHints(VoiceGender.NotSet, VoiceAge.NotSet, 0,
                    System.Globalization.CultureInfo.GetCultureInfo("ko-KR"));
                synth.Rate = TtsRate;
                synth.Volume = 100;
                synth.SetOutputToWaveFile(speechPath);
                synth.Speak(ToKoreanNumbers(text));
                synth.SetOutputToNull();
            }
 
            bool hasChime = _chimePath != null;
            if (hasChime)
                ConcatWav(_chimePath!, speechPath, outPath);
            else
                File.Copy(speechPath, outPath, overwrite: true);
 
            _playlist.Add(outPath);
            SavePlaylist();
 
            _ttsTexts.RemoveAll(t => t == text);
            _ttsTexts.Insert(0, text);
            SaveTtsTexts();
 
            RefreshPlaylistView();
            RefreshTtsHistory();
            _txtTts.Clear();
 
            string msg = hasChime
                ? "음성 추가가 완료되었습니다. (효과음 포함)"
                : "음성 추가가 완료되었습니다.\n효과음 파일(effects\\chime.wav)을 찾지 못해 효과음 없이 추가되었습니다.";
            MessageBox.Show(msg, "완료");
        }
        catch (Exception ex)
        {
            MessageBox.Show("음성 생성 중 오류가 발생했습니다.\n" + ex.Message);
        }
    }
 
    private static void ConcatWav(string firstPath, string secondPath, string outPath)
    {
        using var r1 = new WaveFileReader(firstPath);
        using var r2 = new WaveFileReader(secondPath);
 
        var target = r1.WaveFormat;
        ISampleProvider s1 = r1.ToSampleProvider();
        ISampleProvider s2 = r2.ToSampleProvider();
 
        if (s1.WaveFormat.Channels != target.Channels)
            s1 = target.Channels == 1 ? s1.ToMono() : s1.ToStereo();
 
        if (s2.WaveFormat.Channels != target.Channels)
            s2 = target.Channels == 1 ? s2.ToMono() : s2.ToStereo();
 
        if (s2.WaveFormat.SampleRate != target.SampleRate)
            s2 = new WdlResamplingSampleProvider(s2, target.SampleRate);
 
        var boosted = new VolumeSampleProvider(s2) { Volume = TtsVolumeBoost };
 
        var concat = new ConcatenatingSampleProvider(new[] { s1, boosted });
        WaveFileWriter.CreateWaveFile16(outPath, concat);
    }
 
    // ---------- 플레이리스트 (저장/불러오기) ----------
    private void SavePlaylist()
        => File.WriteAllText(_playlistPath, JsonSerializer.Serialize(_playlist));
 
    private void LoadPlaylist()
    {
        if (!File.Exists(_playlistPath)) return;
        var loaded = JsonSerializer.Deserialize<List<string>>(File.ReadAllText(_playlistPath));
        if (loaded == null) return;
        _playlist.AddRange(loaded.Where(File.Exists));
    }
 
    // ---------- 플레이리스트 편집 ----------
    private void AddSongs()
    {
        using var dlg = new OpenFileDialog
        {
            Filter = "오디오 파일|*.mp3;*.wav",
            Multiselect = true,
            Title = "추가할 파일을 선택하세요"
        };
        if (dlg.ShowDialog() != DialogResult.OK) return;
 
        _playlist.AddRange(dlg.FileNames);
        SavePlaylist();
        RefreshPlaylistView();
    }
 
    private void RemoveCheckedSongs()
    {
        var indexes = new List<int>();
        for (int i = 0; i < _clbPlaylist.Items.Count; i++)
            if (_clbPlaylist.GetItemChecked(i)) indexes.Add(i);
 
        if (indexes.Count == 0)
        {
            MessageBox.Show("삭제할 곡을 체크해 주세요.");
            return;
        }
 
        if (MessageBox.Show($"체크한 {indexes.Count}곡을 삭제할까요?", "확인",
            MessageBoxButtons.YesNo) != DialogResult.Yes) return;
 
        foreach (int i in indexes.OrderByDescending(x => x))
            _playlist.RemoveAt(i);
 
        SavePlaylist();
        RefreshPlaylistView();
    }
 
    private void ClearPlaylist()
    {
        if (_playlist.Count == 0) return;
        if (MessageBox.Show("플레이리스트를 모두 비울까요?", "확인",
            MessageBoxButtons.YesNo) != DialogResult.Yes) return;
        _playlist.Clear();
        SavePlaylist();
        RefreshPlaylistView();
    }
 
    private void RefreshPlaylistView()
    {
        var checkedSet = new HashSet<int>();
        for (int i = 0; i < _clbPlaylist.Items.Count; i++)
            if (_clbPlaylist.GetItemChecked(i)) checkedSet.Add(i);
 
        _clbPlaylist.BeginUpdate();
        _clbPlaylist.Items.Clear();
        for (int i = 0; i < _playlist.Count; i++)
            _clbPlaylist.Items.Add($"{i + 1,2}. {Path.GetFileName(_playlist[i])}",
                checkedSet.Contains(i));
        _clbPlaylist.EndUpdate();
 
        _lblSummary.Text = _playlist.Count == 0
            ? "곡을 추가해 주세요"
            : $"총 {_playlist.Count}곡 · 체크한 곡으로 예약하거나 바로 재생할 수 있습니다";
    }
 
    private List<string> GetCheckedSongs()
    {
        var result = new List<string>();
        for (int i = 0; i < _clbPlaylist.Items.Count; i++)
            if (_clbPlaylist.GetItemChecked(i))
                result.Add(_playlist[i]);
        return result;
    }
 
    // ---------- 예약 관리 ----------
    private string GetSelectedTime24()
    {
        int h12 = int.Parse(_cbHour12.SelectedItem!.ToString()!);
        int min = int.Parse(_cbMinute.SelectedItem!.ToString()!);
        bool pm = _cbAmPm.SelectedIndex == 1;
 
        int h24 = (h12 % 12) + (pm ? 12 : 0);
        return $"{h24:D2}:{min:D2}";
    }
 
    private ListViewItem? GetTargetItem()
    {
        if (_lv.SelectedItems.Count > 0) return _lv.SelectedItems[0];
        return _lv.CheckedItems.Cast<ListViewItem>().FirstOrDefault();
    }
 
    private void LoadSelectedTimeToEditor()
    {
        var item = GetTargetItem();
        if (item == null) return;
        var sch = (Schedule)item.Tag!;
        var parts = sch.Time.Split(':');
        int h24 = int.Parse(parts[0]);
        int min = int.Parse(parts[1]);
 
        _cbEditAmPm.SelectedIndex = h24 < 12 ? 0 : 1;
        int h12 = h24 % 12;
        if (h12 == 0) h12 = 12;
        _cbEditHour12.SelectedIndex = h12 - 1;
        _cbEditMinute.SelectedIndex = min;
    }
 
    private string GetEditTime24()
    {
        int h12 = int.Parse(_cbEditHour12.SelectedItem!.ToString()!);
        int min = int.Parse(_cbEditMinute.SelectedItem!.ToString()!);
        bool pm = _cbEditAmPm.SelectedIndex == 1;
 
        int h24 = (h12 % 12) + (pm ? 12 : 0);
        return $"{h24:D2}:{min:D2}";
    }
 
    private static string ToDisplayTime(string hm)
    {
        var parts = hm.Split(':');
        int h24 = int.Parse(parts[0]);
        int min = int.Parse(parts[1]);
        string ampm = h24 < 12 ? "오전" : "오후";
        int h12 = h24 % 12;
        if (h12 == 0) h12 = 12;
        return $"{ampm} {h12:D2}:{min:D2}";
    }
 
    private void AddSchedule()
    {
        var checkedSongs = GetCheckedSongs();
        if (checkedSongs.Count == 0)
        {
            MessageBox.Show("예약할 곡을 체크해 주세요.");
            return;
        }
        _schedules.Add(new Schedule
        {
            Time = GetSelectedTime24(),
            Mp3Paths = checkedSongs
        });
        _schedules.Sort((a, b) => string.CompareOrdinal(a.Time, b.Time));
        SaveSchedules();
        RefreshList();
        _tabs.SelectedTab = _tabSchedule;
    }
 
    private void ChangeScheduleTime()
    {
        var item = GetTargetItem();
        if (item == null)
        {
            MessageBox.Show("시간을 수정할 예약을 선택하거나 체크해 주세요.");
            return;
        }
 
        var target = (Schedule)item.Tag!;
        string newTime = GetEditTime24();
 
        if (target.Time == newTime)
        {
            MessageBox.Show("현재와 같은 시간입니다.");
            return;
        }
 
        target.Time = newTime;
        target.LastRunDate = null;
 
        _schedules.Sort((a, b) => string.CompareOrdinal(a.Time, b.Time));
        SaveSchedules();
        RefreshList();
        MessageBox.Show($"시간이 {ToDisplayTime(newTime)}(으)로 변경되었습니다.", "완료");
    }
 
    private void RemoveCheckedSchedules()
    {
        var targets = _lv.CheckedItems.Cast<ListViewItem>()
            .Select(i => (Schedule)i.Tag!).ToList();
        if (targets.Count == 0)
        {
            MessageBox.Show("삭제할 예약을 체크해 주세요.");
            return;
        }
        if (MessageBox.Show($"체크한 {targets.Count}개 예약을 삭제할까요?", "확인",
            MessageBoxButtons.YesNo) != DialogResult.Yes) return;
 
        foreach (var sch in targets)
            _schedules.Remove(sch);
        SaveSchedules();
        RefreshList();
    }
 
    private void ClearSchedules()
    {
        if (_schedules.Count == 0) return;
        if (MessageBox.Show("모든 예약을 삭제할까요?", "확인",
            MessageBoxButtons.YesNo) != DialogResult.Yes) return;
 
        _schedules.Clear();
        SaveSchedules();
        RefreshList();
    }
 
    private void RefreshList()
    {
        _lv.BeginUpdate();
        _lv.Items.Clear();
        foreach (var sch in _schedules)
        {
            var item = new ListViewItem(ToDisplayTime(sch.Time)) { Tag = sch };
            item.SubItems.Add($"{sch.Mp3Paths.Count}곡  ·  " +
                string.Join("  →  ", sch.Mp3Paths.Select(Path.GetFileName)));
            _lv.Items.Add(item);
        }
        _lv.EndUpdate();
    }
 
    private void SaveSchedules()
        => File.WriteAllText(_dataPath, JsonSerializer.Serialize(_schedules));
 
    private void LoadSchedules()
    {
        if (!File.Exists(_dataPath)) return;
        var loaded = JsonSerializer.Deserialize<List<Schedule>>(File.ReadAllText(_dataPath));
        if (loaded != null) _schedules.AddRange(loaded);
    }
 
    private void CheckSchedules()
    {
        var now = DateTime.Now;
        string hm = now.ToString("HH:mm");
        string today = now.ToString("yyyy-MM-dd");
 
        foreach (var sch in _schedules)
        {
            if (sch.Time == hm && sch.LastRunDate != today)
            {
                sch.LastRunDate = today;
                SaveSchedules();
                PlayList(sch.Mp3Paths, force: false);
                break;
            }
        }
    }
 
    // ---------- 재생 (대기열) ----------
    private void PlayList(IEnumerable<string> files, bool force)
    {
        if (_announcing && !force) return;
 
        var list = files.Where(File.Exists).ToList();
        if (list.Count == 0)
        {
            MessageBox.Show("재생할 파일이 없거나 파일을 찾을 수 없습니다.");
            return;
        }
 
        FinishPlayback();
 
        _announcing = true;
        SetStatus(true);
 
        // 다른 프로그램 소리를 Fade Out 시간 동안 줄임 (0이면 즉시 음소거)
        StartOthersFade(toZero: true, seconds: (double)_nudFadeOut.Value);
        _guard.Start();
 
        _queue = new Queue<string>(list);
        _queueTotal = list.Count;
        _queueIndex = 0;
 
        PlayNext();
    }
 
    private void PlayNext()
    {
        StopCurrentOnly();
 
        if (_queue.Count == 0)
        {
            FinishPlayback();
            return;
        }
 
        string path = _queue.Dequeue();
        _queueIndex++;
 
        _reader = new AudioFileReader(path);
        var wave = new WaveOut();
        wave.Init(_reader);
        wave.PlaybackStopped += (s, e) =>
            BeginInvoke(new Action(() =>
            {
                if (wave == _player) PlayNext();
            }));
        _player = wave;
        wave.Play();
 
        _lblNowPlaying.Text = $"[{_queueIndex}/{_queueTotal}] {Path.GetFileName(path)}     ";
        _marqueeX = _marqueeArea.ClientSize.Width;
        UpdateProgress();
        _progress.Start();
    }
 
    private void StopCurrentOnly()
    {
        var p = _player;
        var r = _reader;
        _player = null;
        _reader = null;
        p?.Dispose();
        r?.Dispose();
    }
 
    private void UpdateProgress()
    {
        if (_reader == null)
        {
            _lblRemain.Text = "";
            return;
        }
        var remain = _reader.TotalTime - _reader.CurrentTime;
        if (remain < TimeSpan.Zero) remain = TimeSpan.Zero;
        _lblRemain.Text = $"남은 시간 {remain:mm\\:ss}";
    }
 
    private void FinishPlayback()
    {
        _guard.Stop();
        _progress.Stop();
        _queue.Clear();
        StopCurrentOnly();
 
        if (_announcing)
        {
            _announcing = false;
            // 다른 프로그램 소리를 Fade In 시간 동안 원래 볼륨으로 복원
            StartOthersFade(toZero: false, seconds: (double)_nudFadeIn.Value);
        }
        SetStatus(false);
        _lblNowPlaying.Text = "";
        _lblRemain.Text = "";
    }
 
    // ---------- 다른 프로그램 볼륨 페이드 ----------
    // toZero=true : 현재 볼륨 → 0 (Fade Out, 방송 시작)
    // toZero=false: 0 → 저장된 원래 볼륨 (Fade In, 방송 종료)
    private void StartOthersFade(bool toZero, double seconds)
    {
        _fade.Stop();
 
        if (toZero)
        {
            // 원래 볼륨을 저장 (이미 저장된 세션은 유지)
            SaveOthersVolumes();
            _fadingOut = true;
            _fadeFrom = 1f;
            _fadeTo = 0f;
        }
        else
        {
            _fadingOut = false;
            _fadeFrom = 0f;
            _fadeTo = 1f;
        }
 
        _fadeDuration = seconds;
        _fadeStart = DateTime.Now;
 
        if (seconds <= 0)
        {
            ApplyOthersGain(toZero ? 0f : 1f);
            if (!toZero) _savedVolumes.Clear();
            return;
        }
 
        ApplyOthersGain(_fadeFrom);
        _fade.Start();
    }
 
    // 현재 시점의 페이드 배율을 계산해 다른 프로그램에 적용
    private void StepFade()
    {
        double elapsed = (DateTime.Now - _fadeStart).TotalSeconds;
        double t = _fadeDuration <= 0 ? 1 : Math.Min(1, elapsed / _fadeDuration);
        float gain = (float)(_fadeFrom + (_fadeTo - _fadeFrom) * t);
 
        ApplyOthersGain(gain);
 
        if (t >= 1)
        {
            _fade.Stop();
            if (!_fadingOut)
                _savedVolumes.Clear();
        }
    }
 
    // 원래 볼륨(_savedVolumes)에 배율(gain)을 곱해 각 세션에 적용
    private void ApplyOthersGain(float gain)
    {
        using var enumerator = new MMDeviceEnumerator();
        using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
        var sessions = device.AudioSessionManager.Sessions;
 
        for (int i = 0; i < sessions.Count; i++)
        {
            var session = sessions[i];
            if (session.GetProcessID == (uint)_ownPid) continue;
 
            string id = session.GetSessionIdentifier;
            if (_savedVolumes.TryGetValue(id, out float original))
                session.SimpleAudioVolume.Volume = Math.Clamp(original * gain, 0f, 1f);
        }
    }
 
    // 방송 중 새로 시작된 세션도 포함해, 아직 저장되지 않은 세션의 원래 볼륨을 저장
    private void SaveOthersVolumes()
    {
        using var enumerator = new MMDeviceEnumerator();
        using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
        var sessions = device.AudioSessionManager.Sessions;
 
        for (int i = 0; i < sessions.Count; i++)
        {
            var session = sessions[i];
            if (session.GetProcessID == (uint)_ownPid) continue;
 
            string id = session.GetSessionIdentifier;
            if (!_savedVolumes.ContainsKey(id))
                _savedVolumes[id] = session.SimpleAudioVolume.Volume;
        }
    }
 
    // 방송 중 새로 생긴 세션은 즉시 음소거 상태로 맞춤 (원래 볼륨 저장 후)
    private void MuteOthers()
    {
        using var enumerator = new MMDeviceEnumerator();
        using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
        var sessions = device.AudioSessionManager.Sessions;
 
        for (int i = 0; i < sessions.Count; i++)
        {
            var session = sessions[i];
            if (session.GetProcessID == (uint)_ownPid) continue;
 
            string id = session.GetSessionIdentifier;
            if (!_savedVolumes.ContainsKey(id))
                _savedVolumes[id] = session.SimpleAudioVolume.Volume;
 
            // 페이드 중이 아닐 때만 0으로 유지 (페이드 중이면 현재 단계 값 유지)
            if (!_fade.Enabled)
                session.SimpleAudioVolume.Volume = 0f;
        }
    }
}
cs

'바이브코딩' 카테고리의 다른 글

20261024  (0) 2026.10.24
20261018  (0) 2026.10.19