반응형

WPF 에서 가장 쉽게 비디오 플레이 할 수 있는 방법은 바로 기본 Component인 

Media Element를 사용하는 것이다.

 

Window Media에서 지원하는 동영상 파일 종류라면 모두 재생이 가능하며

간단한 방법으로 제어 또한 가능하다.

 

디자인

기본이 되는 파일열기 / 재생 / 중지 / 멈춤 버튼과

플레이시간 대를 바꿔주는 슬라이더와

소리 조절 슬라이더

그리고 현재 플레이 되는 시간을 알려주는 라벨 하나가 있는 간단한 디자인이다.

XAML Source

<Window x:Class="UtilityPackage.MediaElementExample"
        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:UtilityPackage"
        mc:Ignorable="d"
        Title="MediaElementExample" Height="450" Width="541.594">
    <Grid>
        <MediaElement x:Name="mediaMain" Margin="10,10,10,65" 
                      LoadedBehavior="Manual" 
                      UnloadedBehavior="Stop" 
                      MediaOpened="MediaMain_MediaOpened" 
                      MediaEnded="MediaMain_MediaEnded"
                      MediaFailed="MediaMain_MediaFailed"/>
        <Slider x:Name="sldrPlayTime" Margin="10,0,10,42" VerticalAlignment="Bottom"
                Thumb.DragStarted="SldrPlayTime_DragStarted"
                Thumb.DragCompleted="SldrPlayTime_DragCompleted" ValueChanged="SldrPlayTime_ValueChanged"/>
        <Button x:Name="btnStart" Content="▶" HorizontalAlignment="Left" Margin="227,0,0,8" Width="29" Height="23" VerticalAlignment="Bottom" Click="BtnStart_Click" Background="#FFFFF8F8"/>
        <Button x:Name="btnStop" Content="■" HorizontalAlignment="Left" Margin="258,0,0,8" Width="29" Height="23" VerticalAlignment="Bottom" Click="BtnStop_Click" Background="#FFFFF8F8"/>
        <Button x:Name="btnPause" Content="II" HorizontalAlignment="Left" Margin="290,0,0,8" Width="29" Height="23" VerticalAlignment="Bottom" Click="BtnPause_Click" Background="#FFFFF8F8"/>
        <Button x:Name="btnSelectFile" Content="파일열기" Margin="0,0,10,7" HorizontalAlignment="Right" Width="56" Height="24" VerticalAlignment="Bottom" Click="BtnSelectFile_Click" Background="White"/>
        <Label Content="소리" HorizontalAlignment="Left" Margin="324,0,0,5" Height="26" VerticalAlignment="Bottom"/>
        <Slider x:Name="sldrVolume" HorizontalAlignment="Left" Margin="363,0,0,10" Width="100" Height="18" VerticalAlignment="Bottom" 
                Thumb.DragStarted="SldrVolume_DragStarted"
                Thumb.DragCompleted="SldrVolume_DragCompleted" Maximum="1" LargeChange="0.1" Value="0.5" />
        <Label x:Name="lblPlayTime" Content="00:00:00 / 00:00:00" HorizontalAlignment="Left" Margin="10,0,0,7" VerticalAlignment="Bottom" Width="212" Height="23"/>
    </Grid>
</Window>

MediaElement는 반드시 LoadBehavier 속성을 지정해주어야 한다. 여기서는 파일을 직접 선택할 것이기 때문에 Manual로 지정하였다.

SliderThumb.DragStarted / Thumb.DragCompleted 이벤트처리로 볼륨 조절과 플레이 시간대를 이동하기 위해 추가하였다.

 

CS

미디어 파일의 시간대를 제어는 TimerTickHandler를 사용한다.

다음과 같은 순서로 소스를 보면 된다.

 

 - 미디어 재생: 파일열기(BtnSelectFile_Click) > TimerTickHandler 초기화 > MediaMain_MediaOpened

 - 플레이 시간대 변경: SldrPlayTime_DragStarted > SldrPlayTime_DragCompleted > SldrPlayTime_ValueChanged

using Microsoft.Win32;
using System;
using System.Windows;
using System.Windows.Threading;

namespace UtilityPackage
{
   
    public partial class MediaElementExample : Window
    {
        bool sldrDragStart = false;

        public MediaElementExample()
        {
            InitializeComponent();
        }

        private void MediaMain_MediaOpened(object sender, RoutedEventArgs e)
        {
            // 미디어 파일이 열리면, 플레이타임 슬라이더의 값을 초기화 한다.
            sldrPlayTime.Minimum = 0;
            sldrPlayTime.Maximum = mediaMain.NaturalDuration.TimeSpan.TotalSeconds;
        }

        private void MediaMain_MediaEnded(object sender, RoutedEventArgs e)
        {
            // 미디어 중지
            mediaMain.Stop();
        }

        private void MediaMain_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            // 미디어 파일 실행 오류시
            MessageBox.Show("동영상 재생 실패 : " + e.ErrorException.Message.ToString());
        }

        private void BtnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            // Win32 DLL 을 사용하여 선택할 파일 다이얼로그를 실행한다.
            OpenFileDialog dlg = new OpenFileDialog()
            {
                DefaultExt = ".avi",
                Filter = "All files (*.*)|*.*",
                Multiselect = false
            };

            if (dlg.ShowDialog() == true)
            {
                // 선택한 파일을 Media Element에 지정하고 초기화한다.
                mediaMain.Source = new Uri(dlg.FileName);
                mediaMain.Volume = 0.5;
                mediaMain.SpeedRatio = 1;

                // 동영상 파일의 Timespan 제어를 위해 초기화와 이벤트처리기를 추가한다.
                DispatcherTimer timer = new DispatcherTimer()
                {
                    Interval = TimeSpan.FromSeconds(1)
                };
                timer.Tick += TimerTickHandler;
                timer.Start();

                // 선택한 파일을 실행
                mediaMain.Play();
            }
        }

        // 미디어파일 타임 핸들러
        // 미디어파일의 실행시간이 변경되면 호출된다.
        void TimerTickHandler(object sender, EventArgs e)
        {
            // 미디어파일 실행시간이 변경되었을 때 사용자가 임의로 변경하는 중인지를 체크한다.
            if (sldrDragStart)
                return;

            if (mediaMain.Source == null
                || !mediaMain.NaturalDuration.HasTimeSpan)
            {
                lblPlayTime.Content = "No file selected...";
                return;
            }

            // 미디어 파일 총 시간을 슬라이더와 동기화한다.
            sldrPlayTime.Value = mediaMain.Position.TotalSeconds;
        }

        private void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            if (mediaMain.Source == null)
                return;

            mediaMain.Play();
        }

        private void BtnStop_Click(object sender, RoutedEventArgs e)
        {
            if (mediaMain.Source == null)
                return;

            mediaMain.Stop();
        }

        private void BtnPause_Click(object sender, RoutedEventArgs e)
        {
            if (mediaMain.Source == null)
                return;

            mediaMain.Pause();
        }

        private void SldrVolume_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
        {
            
        }

        private void SldrVolume_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            // 사용자가 변경한 볼륨값으로 미디어 볼륨값을 변경한다.
            mediaMain.Volume = sldrPlayTime.Value;
        }

        private void SldrPlayTime_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
        {
            // 사용자가 시간대를 변경하면, 잠시 미디어 재생을 멈춘다.
            sldrDragStart = true;
            mediaMain.Pause();
        }

        private void SldrPlayTime_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            // 사용자가 지정한 시간대로 이동하면, 이동한 시간대로 값을 지정한다.
            mediaMain.Position = TimeSpan.FromSeconds(sldrPlayTime.Value);

            // 멈췄던 미디어를 재실행한다.
            mediaMain.Play();
            sldrDragStart = false;
        }

        private void SldrPlayTime_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (mediaMain.Source == null)
                return;

            // 플레이시간이 변경되면, 표시영역을 업데이트한다.
            lblPlayTime.Content = String.Format("{0} / {1}", mediaMain.Position.ToString(@"mm\:ss"), mediaMain.NaturalDuration.TimeSpan.ToString(@"mm\:ss"));
        }

    }
}

 

 

참고 사이트

 - https://www.wpf-tutorial.com/audio-video/playing-video/

 

Playing video - The complete WPF tutorial

Audio & Video: Playing videoIn the previous article, we used the MediaPlayer class to play an MP3 file, but the cool part about the MediaPlayer class is that it can work with video files as well. However, since a video actually needs to be displayed somewh

www.wpf-tutorial.com

https://docs.microsoft.com/ko-kr/dotnet/framework/wpf/graphics-multimedia/how-to-control-a-mediaelement-play-pause-stop-volume-and-speed

 

방법: MediaElement 제어(재생, 일시 중지, 정지, 볼륨 및 속도)

이 문서의 내용 --> 다음 예제에서는 사용 하 여 미디어 재생을 제어 하는 방법을 보여 줍니다는 MediaElement합니다.The following example shows how to control playback of media using a MediaElement. 이 예제에서는 재생, 일시 중지, 중지 및 미디어에서 앞뒤로 건너뛸 뿐만 볼륨 및 속도 비율을 조정할 수 있는 간단한 미디어 플레이어를 만듭니다.The example creates a

docs.microsoft.com

 

반응형

WRITTEN BY
데르벨준

,