안녕하세요? HappyBono 인사드립니다.
이번에는 음악을 재생하는 미디어 플레이어를 구현해보는 시간을 가져보도록 하겠습니다.
Visual Studio 를 실행하신 후 WPF App 형식을 선택하신 후 하단의 [Next] 버튼을 눌러 진행합니다.

프로젝트 이름은 “MediaPlayerSample” 로 입력해주시고, 하단의 [Create] 버튼을 클릭하셔서 새 프로젝트를 생성합니다.

폼은 아래와 같이 Label 과 Button, 그리고 Slider 컨트롤을 사용하여 디자인합니다.

| Control | Name | Content |
| Button | playButton | Play |
| Button | pauseButton | Pause |
| Button | stopButton | Stop |
| Button | loadButton | Open |
| Label | volumeLabel | Volume : 0 |
| Label | progressLabel | 00:00 |
| Label | separatorLabel | / |
| Label | totalTimeLabel | 00:00 |
| Label | artistNameLabel | artistName |
| Label | songTitleLabel | songTitle |
| Label | albumTitleLabel | albumTitle |
| Slider | volumeSlider | – |
| Slider | progressSlider | – |
<Window x:Class="MediaPlayerSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MediaPlayerSample"
mc:Ignorable="d"
Title="MediaPlayerSample" Height="239.276" Width="592.343" ResizeMode="CanMinimize">
<Grid>
<Button x:Name="playButton" Content="Play" HorizontalAlignment="Left" Height="27" Margin="39,146,0,0" VerticalAlignment="Top" Width="72" Click="playButton_Click"/>
<Button x:Name="pauseButton" Content="Pause" HorizontalAlignment="Left" Height="27" Margin="116,146,0,0" VerticalAlignment="Top" Width="72" Click="pauseButton_Click"/>
<Button x:Name="stopButton" Content="Stop" HorizontalAlignment="Left" Height="27" Margin="193,146,0,0" VerticalAlignment="Top" Width="72" Click="stopButton_Click"/>
<Button x:Name="loadButton" Content="Open" HorizontalAlignment="Left" Height="27" Margin="279,146,0,0" VerticalAlignment="Top" Width="72" Click="loadButton_Click"/>
<Label x:Name="volumeLabel" Content="Volume : 0" HorizontalAlignment="Left" Height="26" Margin="464,149,0,0" VerticalAlignment="Top" Width="96"/>
<Label x:Name="progressLabel" Content="00:00" Height="26" Margin="464,109,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="39"/>
<Label x:Name="separatorLabel" Content="/" Height="26" Margin="502,109,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="22"/>
<Label x:Name="totalTimeLabel" Content="00:00" Height="26" Margin="519,109,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="39"/>
<Label x:Name="artistNameLabel" Content="artistName" HorizontalAlignment="Left" Margin="39,67,0,0" VerticalAlignment="Top" Width="521"/>
<Label x:Name="songTitleLabel" Content="songTitle" HorizontalAlignment="Left" Margin="39,41,0,0" VerticalAlignment="Top" Width="521"/>
<Label x:Name="albumTitleLabel" Content="albumTitle" HorizontalAlignment="Left" Margin="39,15,0,0" VerticalAlignment="Top" Width="521"/>
<Slider x:Name="volumeSlider" HorizontalAlignment="Left" Height="22" Margin="372,151,0,0" VerticalAlignment="Top" Width="79" ValueChanged="volumeSlider_ValueChanged"/>
<Slider x:Name= "progressSlider" HorizontalAlignment="Left" Height="20" Margin="39,111,0,0" VerticalAlignment="Top" Width="412" ValueChanged="progressSlider_ValueChanged" Thumb.DragDelta="progressSlider_DragDelta" />
</Grid>
</Window>
디자인 작업을 모두 완료하셨다면, 폼 최상단에 System.Windows.Media 를 참조할 수 있도록 Namespace 를 선언해줍니다.
using System.Windows.Media;
그리고 MediaPlayer Class 를 이용해 새로운 MediaPlayer 하나를 생성합니다.
private MediaPlayer sampleMediaPlayer = new MediaPlayer();
이후, loadButton (파일 열기 버튼) 의 클릭 이벤트에 파일 열기 대화상자를 표시한 후 사용자가 선택한 음악을 불러와 재생해주면 됩니다.
string filePath;
private void loadButton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();
openFileDlg.DefaultExt = ".mp3";
openFileDlg.Filter = "MP3 file (.mp3)|*.mp3";
Nullable<bool> result = openFileDlg.ShowDialog();
if (result == true)
{
filePath = openFileDlg.FileName;
sampleMediaPlayer.Open(new Uri(filePath));
sampleMediaPlayer.MediaOpened += loadedMusic;
sampleMediaPlayer.Play();
}
}
stopButton 의 클릭 이벤트에는 MediaPlayer.Stop() 메소드를 사용하여 재생되던 음악을 정지하도록 구현하고,
private void stopButton_Click(object sender, RoutedEventArgs e)
{
sampleMediaPlayer.Stop();
}
pauseButton 에 할당된 클릭 이벤트에도 마찬가지로 음악이 일시정지되도록 아래와 같이 MediaPlayer.Pause 메소드를 사용하시면 되며,
private void pauseButton_Click(object sender, RoutedEventArgs e)
{
sampleMediaPlayer.Pause();
}
playButton 에도 비슷하게 MediaPlayer 컨트롤에서 제공하는 Play 메소드를 사용하여 간단하게 재생 기능을 구현하실 수 있습니다.
private void playButton_Click(object sender, RoutedEventArgs e)
{
sampleMediaPlayer.Play();
}
음악 재생에 따라 슬라이더가 움직이는 부분은 Thread 를 사용하여 밀리초마다 value 값을 증가시키고, 현재 값을 화면에 표시하는 방식으로 작동합니다.
public delegate void timeTick();
DispatcherTimer ticks = new DispatcherTimer();
private void loadedMusic(object sender, EventArgs e)
{
progressSlider.Maximum = sampleMediaPlayer.NaturalDuration.TimeSpan.TotalMilliseconds;
totalTimeLabel.Content = sampleMediaPlayer.NaturalDuration.TimeSpan.ToString(@"mm\:ss");
ticks.Interval = TimeSpan.FromMilliseconds(1);
ticks.Tick += ticks_Tick;
ticks.Start();
}
void ticks_Tick(object sender, object e)
{
TimeSpan newTimeSpan = sampleMediaPlayer.Position;
progressSlider.Value = newTimeSpan.TotalMilliseconds;
progressLabel.Content = newTimeSpan.ToString("mm':'ss':'ff");
}
직접 슬라이더를 변경하거나 드래그했을 경우에는 Thumb.DragDelta 이벤트를 활용하여 아래와 같이 코드를 작성했습니다.
private void progressSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
TimeSpan newTimeSpan = sampleMediaPlayer.Position;
progressLabel.Content = newTimeSpan.ToString(@"mm\:ss");
}
private void progressSlider_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
sampleMediaPlayer.Position = new TimeSpan(0, 0, 0, 0, (int)progressSlider.Value);
TimeSpan newTimeSpan = sampleMediaPlayer.Position;
progressLabel.Content = newTimeSpan.ToString(@"mm\:ss");
}
결과적으로 음악의 재생 및 재생 중인 시간 및 전체 시간 표시, 볼륨 표시, 슬라이더 컨트롤이 정상적으로 작동하는 것을 확인하실 수 있습니다.

고맙습니다!

좋은 내용 잘 보았습니다. 그러나 한곡이 아닌 20여곡을 Form의 리스트에 불러올때 각 곡마다 재생시간을 추출하고 싶은데 잘 안되네요. 좋은 방법있는지요?