Windows 8: How to play a video from a local Visual Studio Project Folder
- Problem
- It is fairly easy to play a video from the videos library folder.
- It is well documented in the "Media Play To" sample
**The XAML Code
**
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <Page x:Class="HelloVideo.MainPage" IsTabStop="false" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:HelloVideo" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <MediaElement x:Name="player" HorizontalAlignment="Left" AutoPlay="True"/> </Grid> </Page> |
- Notice the MediaElement on lines 11-14
- It is used to play the video
- Properties
- It needs a name for the code behind (player)
- I align it horizontally to the left
- It plays automatically as soon as a video is assigned to it
The Code Behind
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | using System; using System.Collections.Generic; using System.IO; using System.Linq; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage; using Windows.Storage.Pickers; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace HelloVideo { public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } async protected override void OnNavigatedTo(NavigationEventArgs e) { // Get to the Assets folder in Visual Studio StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets"); // Get the video we wish to play from the folder above StorageFile localVideo = await folder.GetFileAsync("RunFiddler.wmv"); try { if (localVideo != null) { // Read the video as a stream var stream = await localVideo.OpenAsync(FileAccessMode.Read); // Tell the player to read the stream and indicate the video type (video/wmv) player.SetSource(stream, localVideo.ContentType); } } catch (Exception) { throw; } } } } |
Conclusion Playing a video from a local folder in Visual Studio is easy, once you spend all the time to figure it out as I did. This same technique can be used with almost any file, not just videos. This took me way too long to figure it out. Some days my game is off. I thought I’d pass along my discoveries. Thanks for reading.