WPF播放視訊

weixin_33912246發表於2018-11-12
原文:WPF播放視訊

在現在的專案中需要使用到播放視訊的功能,本來打算使用VLC來做的。後來發現WPF 4.0之後新增了MediaElement類,可以實現視訊播放。

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid Background="Black">
            <MediaElement x:Name="MediaPlayer" LoadedBehavior="Manual" MediaOpened="MediaPlayer_MediaOpened" />
        </Grid>

        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <StackPanel Grid.Column="1" Orientation="Horizontal">
                <Button x:Name="ButtonOpen" Click="ButtonOpen_Click" Content="Open..." Width="100" Height="25" Margin="5"/>
                <Button x:Name="ButtonPlay" Click="ButtonPlay_Click" Content="Play" Width="100" Height="25" Margin="5" />
                <Button x:Name="ButtonStop" Click="ButtonStop_Click" Content="Stop" Width="100" Height="25" Margin="5" />
                <Button x:Name="ButtonForward" Click="ButtonForward_Click" Content="Forward" Width="100" Height="25" Margin="5" />
                <Button x:Name="ButtonBack" Click="ButtonBack_Click" Content="Back" Width="100" Height="25" Margin="5" />
            </StackPanel>
        </Grid>
    </Grid>
    private string _videoPath;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void ButtonOpen_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialog = new OpenFileDialog();

        dialog.Filter = "Video File(*.avi;*.mp4;*.mkv;*.wav;*.rmvb)|*.avi;*.mp4;*.mkv;*.wav;*.rmvb|All File(*.*)|*.*";

        if(dialog.ShowDialog().GetValueOrDefault())
        {
            _videoPath = dialog.FileName;
        }
    }

    private void ButtonPlay_Click(object sender, RoutedEventArgs e)
    {
        MediaPlayer.Source = new Uri(_videoPath);

        MediaPlayer.Play();
    }

    private void ButtonStop_Click(object sender, RoutedEventArgs e)
    {
        MediaPlayer.Stop();
    }

    private void ButtonForward_Click(object sender, RoutedEventArgs e)
    {
        MediaPlayer.Position = MediaPlayer.Position + TimeSpan.FromSeconds(20);
    }

    private void ButtonBack_Click(object sender, RoutedEventArgs e)
    {
        MediaPlayer.Position = MediaPlayer.Position - TimeSpan.FromSeconds(20);
    }

    private void MediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
    {
        // Get the lenght of the video
        int duration = MediaPlayer.NaturalDuration.TimeSpan.Seconds;
    }

這樣就可以簡單的實現對視訊的播放,暫停,快進,快退等。不過MediaElement是有缺陷的,它支援的視訊格式和Windows Media Player一樣。可以把MediaElement看成是WMP的一個WPF元件。如果要播放WMP不支援的格式。

1. 使用VLC開源庫,支援的視訊格式非常多,地址:https://github.com/videolan/vlc

2. 在本地安裝解碼器元件,類似的有:K-Lite Codec Pack

這樣就可以實現一個WPF版本的"萬能播放器"。

感謝您的閱讀,程式碼點選這裡下載。

相關文章