Include your media file to project as embedded resources. This is easier because of it is necessary to know the file extension when saving to disk. The MediaTimeline
elements requires the file extension, does not support a stream.
Then extract audio/media content from a resources and write it to the temporary file. Then set URI for the MediaTimeline
source to make reference to the temporary file.
Code behind:
private string MediaFilePathName { get; set; }
var resourceName = "[YourAssemblyName][.Folder].Movie.mp4"; // NOTE: Case sensitive
using (var fstream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
var ext = resourceName.Substring(resourceName.LastIndexOf("."));
var pathfile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ext;
using (FileStream outputFileStream = new FileStream(pathfile, FileMode.Create))
{
fstream.CopyTo(outputFileStream);
}
media.Source = new Uri(pathfile, UriKind.RelativeOrAbsolute);
MediaFilePathName = pathfile;
}
In the XAML:
<Window ... Closed="Window_Closed">
<Grid>
<MediaElement x:Name="audio">
<MediaElement.Triggers>
<EventTrigger RoutedEvent="MediaElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<MediaTimeline x:Name="media" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</MediaElement.Triggers>
</MediaElement>
</Grid>
</Window>
The temporary file should be deleted when it no longer needed:
private void Window_Closed(object sender, EventArgs e)
{
if (File.Exists(MediaFilePathName))
{
File.Delete(MediaFilePathName);
}
}
Another way to use third party library that will execute all the steps.