Reputation: 1751
I try to make a Media Player on WPF.
I made this yet :
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();
}
}
}
And the XAML file :
<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>
But, the video never start, and the window stay white.
Help please :)
ps : sorry for my bad english
Upvotes: 0
Views: 1879
Reputation: 19296
MediaPlayer Class (msdn):
MediaPlayer is different from a MediaElement in that it is not a control that can be added directly to the user interface (UI) of an application. To display media loaded using MediaPlayer, a VideoDrawing or DrawingContext must be used.
So if you want to use MediaPlayer you should use 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;
...
In this solution you don't have to add MediaElement
in XAML.
To play media in XAML only, use a MediaElement
(msdn).
XAML:
<MediaElement Name="McMediaElement" Source="D:\test.avi"
LoadedBehavior="Play" UnloadedBehavior="Stop" Stretch="Fill"
Margin="10,10,10,0" Width="450" Height="250"
/>
Code-behind:
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);
}
}
Upvotes: 1