C#WPF媒体视频播放器无法启动

时间:2013-11-13 18:45:57

标签: c# wpf video media-player

我尝试在WPF上制作媒体播放器。

我做到了这一点:

     public partial class MyMediaPlayer : Window
    {
        public MyMediaPlayer()
        {
            InitializeComponent();

            //

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = "c:\\"; // init

            dlg.Filter = "All Files (*.*)|*.*"; // filter
            dlg.RestoreDirectory = true;
            // dialog window
          if (dlg.ShowDialog() == true) // checked ? 
            {
                string selectedFileName = dlg.FileName; // path of the media
                MediaPlayer player = new MediaPlayer();
                player.Open(new Uri(selectedFileName, UriKind.Relative));
                VideoDrawing aVideoDrawing = new VideoDrawing();
                aVideoDrawing.Rect = new Rect(0, 0, 100, 100);
                aVideoDrawing.Player = player; // play
                // never play
                player.Play();
            }
        }
    }

和XAML文件:

    <Window ... >
    <Grid>
        <MediaElement Margin="10,10,10,0 " Source="D:\test.avi"
                              Name="McMediaElement"
                 Width="450" Height="250" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill"
                 />
    </Grid>
</Window>

但是,视频永远不会启动,窗口会保持白色。

请帮助:)

ps:抱歉我的英文不好

1 个答案:

答案 0 :(得分:0)

MediaPlayer类(msdn):

  

MediaPlayer与MediaElement的不同之处在于它不是   可以直接添加到用户界面(UI)的控件   应用。要显示使用MediaPlayer加载的媒体,请使用VideoDrawing   或者必须使用DrawingContext。

因此,如果您想使用MediaPlayer,则应使用DrawingBrush class:

...
string selectedFileName = dlg.FileName; 
MediaPlayer player = new MediaPlayer();
player.Open(new Uri(selectedFileName, UriKind.Relative));
VideoDrawing aVideoDrawing = new VideoDrawing();
aVideoDrawing.Rect = new Rect(0, 0, 100, 100);
aVideoDrawing.Player = player;                 
player.Play();
DrawingBrush DBrush = new DrawingBrush(aVideoDrawing);
this.Background = DBrush;
...

在此解决方案中,您不必在XAML中添加MediaElement

要仅在XAML中播放媒体,请使用MediaElementmsdn)。

XAML:

<MediaElement  Name="McMediaElement" Source="D:\test.avi"
         LoadedBehavior="Play" UnloadedBehavior="Stop" Stretch="Fill"
         Margin="10,10,10,0" Width="450" Height="250"
            />

代码隐藏:

public MainWindow()
{
    InitializeComponent();

    OpenFileDialog dlg = new OpenFileDialog();
    dlg.InitialDirectory = "c:\\"; 

    dlg.Filter = "All Files (*.*)|*.*"; // filter
    dlg.RestoreDirectory = true;    
    if (dlg.ShowDialog() == true) 
    {
        string selectedFileName = dlg.FileName;     
        McMediaElement.Source = new Uri(selectedFileName, UriKind.Absolute);        
    }
}