매장 안내 방송_Piper
Announce Player_Piper

* WinForms로 제작된 알파버전이므로, 추가 지원 및 업데이트를 하지 않습니다.
** 이 프로그램은 클로드를 이용하여 바이브코딩으로 **C#**으로 작성했습니다.
*** 개발 환경은 .NET 10, UI는 WinForms,
음성 생성은 System.Speech (Windows 내장 TTS) → Piper(외부 실행 파일),
오디오 재생과 볼륨 제어는 NAudio를 사용합니다.
숫자 입력 시,
* 띄워쓰기를 넣어서 입력
→ 123가4567 (X) 1 2 3 가 4 5 6 7 (O)
* 원 단위는 , (쉼표)를 넣어서 입력
→ 1000 (X) / 1,000 (O)
* 단위 인식 불가, 한글로 입력
→ 1단 (X) / 한단 (O)
BOX.NET 다운로드
... 를 누른 후, 다운로드 를 누르세요!
using NAudio.CoreAudioApi;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using Microsoft.Win32;
using System.Diagnostics;
using System.Linq;
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 float TtsVolumeBoost = 2.0f;
// Piper 음성 속도 배율 (1.0 기본, 클수록 느림)
private const double PiperLengthScale = 1.15;
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"));
// Piper 경로 (실행 폴더 기준 상위로 찾음)
private readonly string? _piperExe = FindProjectFile(Path.Combine("piper", "piper.exe"));
private readonly string? _piperModel = FindProjectFile(Path.Combine("piper", "model", "ko_KR-kss-medium.onnx"));
// ---------- 데이터 / 상태 ----------
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;
private float _fadeTo = 1f;
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);
_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);
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 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 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 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();
}
}
// ---------- 숫자 → 한글 수사 변환 ----------
// 1) 천 단위 쉼표 숫자(5,900)는 통째로 읽음
// 2) 띄어쓰기로 떨어진 한 자리 숫자(1 2 3)는 쉼표로 끊어 읽음
// 3) 숫자와 한글 사이 띄어쓰기도 쉼표로 쉬게 함
private static string ToKoreanNumbers(string text)
{
// 천 단위 쉼표 숫자를 먼저 한글로 변환 (쉼표 포함 패턴만)
string s = Regex.Replace(text, @"\d{1,3}(,\d{3})+", m =>
NumberToKorean(m.Value.Replace(",", "")));
// 숫자(한글로 바뀌지 않은 것)와 숫자/한글 사이 띄어쓰기를 쉼표로 변경
s = Regex.Replace(s, @"(?<=\d)\s+(?=[\d가-힣])|(?<=[가-힣])\s+(?=\d)", ", ");
// 남은 한 자리 이상 숫자를 자리마다 쉼표로 구분해 읽음
s = Regex.Replace(s, @"\d+", m =>
string.Join(", ", m.Value.Select(c => NumberToKorean(c.ToString()))));
return s;
}
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();
}
// ---------- Piper TTS (텍스트 → WAV) ----------
private void SynthesizeWithPiper(string text, string outWavPath)
{
if (_piperExe == null || _piperModel == null)
throw new FileNotFoundException(
"Piper 실행 파일 또는 한국어 모델을 찾지 못했습니다.\n" +
"piper\\piper.exe 와 piper\\model\\ko_KR-kss-medium.onnx 를 확인하세요.");
var psi = new ProcessStartInfo
{
FileName = _piperExe,
Arguments = $"--model \"{_piperModel}\" --output_file \"{outWavPath}\" --length_scale {PiperLengthScale.ToString(System.Globalization.CultureInfo.InvariantCulture)}",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = true,
StandardInputEncoding = Encoding.UTF8,
WorkingDirectory = Path.GetDirectoryName(_piperExe)!
};
using var proc = Process.Start(psi)!;
proc.StandardInput.WriteLine(text);
proc.StandardInput.Close();
string err = proc.StandardError.ReadToEnd();
proc.WaitForExit();
if (proc.ExitCode != 0 || !File.Exists(outWavPath))
throw new InvalidOperationException("Piper 실행 실패:\n" + err);
}
// ---------- 예시 문구 관리 ----------
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 (Piper → 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");
SynthesizeWithPiper(ToKoreanNumbers(text), speechPath);
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);
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;
StartOthersFade(toZero: false, seconds: (double)_nudFadeIn.Value);
}
SetStatus(false);
_lblNowPlaying.Text = "";
_lblRemain.Text = "";
}
// ---------- 다른 프로그램 볼륨 페이드 ----------
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();
}
}
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;
if (!_fade.Enabled)
session.SimpleAudioVolume.Volume = 0f;
}
}
}




