Quickstart: Using Play To in applications (XAML)
[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]
You can use Play To to enable users to easily stream audio, video, or images from their computer to devices in their home network. This topic shows you how to use Play To in an application, to enable users to stream media to a target device.
Roadmap: How does this topic relate to others? See:
- Roadmap for Windows Runtime apps using C# or Visual Basic
- Roadmap for Windows Runtime apps using C++
Objective: Use Play To to stream media to a target device.
Prerequisites
Microsoft Visual Studio
Instructions
1. Create a new project and enable access to media libraries
- Open Visual Studio and select New Project from the File menu. In the Visual C# or Visual Basic section, select Application. Name the application PlayToSample and click OK.
- Open the package.appxmanifest file and select the Capabilities tab. Select the Music Library, Pictures Library, and Videos Library capabilities to enable your application to access the media libraries on a computer. Close and save the manifest file.
2. Add XAML UI
Open the MainPage.xaml file and add the following markup in place of the default <Grid> element.
<Grid.RowDefinitions> <RowDefinition Height="40" /> <RowDefinition Height="338" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Canvas x:Name="ButtonCanvas" Grid.Row="0"> <Button x:Name="VideoButton" Click="VideoButtonClick" Content="Video" Margin="8,8,0,724" /> <Button x:Name="AudioButton" Click="AudioButtonClick" Content="Audio" Margin="102,8,0,724" /> <Button x:Name="ImageButton" Click="ImageButtonClick" Content="Image" Margin="196,8,0,724" /> </Canvas> <Canvas x:Name="DisplayCanvas" Grid.Row="1" Height="338" VerticalAlignment="Top" HorizontalAlignment="Left" Width="600"> <MediaElement x:Name="VideoPlayer" HorizontalAlignment="Left" Height="338" VerticalAlignment="Top" Width="600" /> <MediaElement x:Name="AudioPlayer" HorizontalAlignment="Left" Height="338" VerticalAlignment="Top" Width="600" /> <Image x:Name="ImagePlayer" HorizontalAlignment="Left" Height="338" VerticalAlignment="Top" Width="600" /> </Canvas> <TextBlock x:Name="MessageBlock" Grid.Row="2" HorizontalAlignment="Left" Height="140" TextWrapping="Wrap" VerticalAlignment="Top" Width="600"/>
3. Add initialization code
The code in this step creates the event handlers for the click events of the buttons. The ShowMedia function toggles which of the elements are visible for video, audio and images. It also retains a reference to the active element. This reference is passed to the PlayToManager to stream the source of the element to the Play To target.
Open the MainPage.xaml.cs or MainPage.xaml.vb file and add the following code to the MainPage class.
// Save a reference to the current media element for PlayTo. private FrameworkElement mediaElement; private void ShowMedia(string mediaName) { VideoPlayer.Visibility = Visibility.Collapsed; VideoPlayer.Pause(); AudioPlayer.Visibility = Visibility.Collapsed; AudioPlayer.Pause(); ImagePlayer.Visibility = Visibility.Collapsed; FrameworkElement f = (FrameworkElement)DisplayCanvas.FindName(mediaName); f.Visibility = Visibility.Visible; switch (mediaName) { case "VideoPlayer": mediaElement = VideoPlayer; break; case "AudioPlayer": mediaElement = AudioPlayer; break; case "ImagePlayer": mediaElement = ImagePlayer; break; } } private void VideoButtonClick(object sender, RoutedEventArgs e) { ShowMedia("VideoPlayer"); LoadVideo(); } private void AudioButtonClick(object sender, RoutedEventArgs e) { ShowMedia("AudioPlayer"); LoadAudio(); } private void ImageButtonClick(object sender, RoutedEventArgs e) { ShowMedia("ImagePlayer"); LoadImage(); }
' Save a reference to the current media element for PlayTo. Private mediaElement As FrameworkElement Private Sub ShowMedia(mediaName As String) VideoPlayer.Visibility = Visibility.Collapsed VideoPlayer.Pause() AudioPlayer.Visibility = Visibility.Collapsed AudioPlayer.Pause() ImagePlayer.Visibility = Visibility.Collapsed Dim f = CType(DisplayCanvas.FindName(mediaName), FrameworkElement) f.Visibility = Visibility.Visible Select mediaName Case "VideoPlayer" mediaElement = VideoPlayer Case "AudioPlayer" mediaElement = AudioPlayer Case "ImagePlayer" mediaElement = ImagePlayer End Select End Sub Private Sub VideoButtonClick() ShowMedia("VideoPlayer") LoadVideo() End Sub Private Sub AudioButtonClick() ShowMedia("AudioPlayer") LoadAudio() End Sub Private Sub ImageButtonClick() ShowMedia("ImagePlayer") LoadImage() End Sub
4. Add code to get media source from the local media libraries
The code in this step is called during the click events of the buttons. Each method takes the first item found in the selected media library and plays or displays it in the related media or image element. For example, if you click the Video button in the application, then the LoadVideo function gets the first video from the Video folder, sets it as the source for the <MediaElement> tag used for video, and then plays the video.
In the MainPage.xaml.cs or MainPage.xaml.vb file, add the following code after the code from the previous step.
async private void LoadVideo() { try { IReadOnlyList<Windows.Storage.StorageFile> resultsLibrary = await Windows.Storage.KnownFolders.VideosLibrary.GetFilesAsync(); MessageBlock.Text += "Play video: " + resultsLibrary[0].Name + "\n"; Windows.Storage.Streams.IRandomAccessStream videoStream = await resultsLibrary[0].OpenAsync(Windows.Storage.FileAccessMode.Read); VideoPlayer.SetSource(videoStream, resultsLibrary[0].FileType); VideoPlayer.Play(); } catch (Exception ex) { MessageBlock.Text += "Exception encountered: " + ex.Message + "\n"; } } async private void LoadAudio() { try { IReadOnlyList<Windows.Storage.StorageFile> resultsLibrary = await Windows.Storage.KnownFolders.MusicLibrary.GetFilesAsync(); MessageBlock.Text += "Play audio: " + resultsLibrary[0].Name + "\n"; Windows.Storage.Streams.IRandomAccessStream audioStream = await resultsLibrary[0].OpenAsync(Windows.Storage.FileAccessMode.Read); AudioPlayer.SetSource(audioStream, resultsLibrary[0].FileType); AudioPlayer.Play(); } catch (Exception ex) { MessageBlock.Text += "Exception encountered: " + ex.Message + "\n"; } } async private void LoadImage() { try { IReadOnlyList<Windows.Storage.StorageFile> resultsLibrary = await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync(); MessageBlock.Text += "Show image: " + resultsLibrary[0].Name + "\n"; Windows.Storage.Streams.IRandomAccessStream imageStream = await resultsLibrary[0].OpenAsync(Windows.Storage.FileAccessMode.Read); Windows.UI.Xaml.Media.Imaging.BitmapImage imageBitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); imageBitmap.SetSource(imageStream); ImagePlayer.Source = imageBitmap; } catch (Exception ex) { MessageBlock.Text += "Exception encountered: " + ex.Message + "\n"; } }
Private Async Sub LoadVideo() Try Dim resultsLibrary = Await Windows.Storage.KnownFolders.VideosLibrary.GetFilesAsync() MessageBlock.Text &= "Play video: " & resultsLibrary(0).Name & vbCrLf Dim videoStream = Await resultsLibrary(0).OpenAsync(Windows.Storage.FileAccessMode.Read) VideoPlayer.SetSource(videoStream, resultsLibrary(0).FileType) VideoPlayer.Play() Catch ex As Exception MessageBlock.Text &= "Exception encountered: " & ex.Message & vbCrLf End Try End Sub Private Async Sub LoadAudio() Try Dim resultsLibrary = Await Windows.Storage.KnownFolders.MusicLibrary.GetFilesAsync() MessageBlock.Text &= "Play audio: " & resultsLibrary(0).Name & vbCrLf Dim audioStream = Await resultsLibrary(0).OpenAsync(Windows.Storage.FileAccessMode.Read) AudioPlayer.SetSource(audioStream, resultsLibrary(0).FileType) AudioPlayer.Play() Catch ex As Exception MessageBlock.Text &= "Exception encountered: " & ex.Message & vbCrLf End Try End Sub Private Async Sub LoadImage() Try Dim resultsLibrary = Await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync() MessageBlock.Text &= "Show image: " & resultsLibrary(0).Name & vbCrLf Dim imageStream = Await resultsLibrary(0).OpenAsync(Windows.Storage.FileAccessMode.Read) Dim imageBitmap = New Windows.UI.Xaml.Media.Imaging.BitmapImage() imageBitmap.SetSource(imageStream) ImagePlayer.Source = imageBitmap Catch ex As Exception MessageBlock.Text &= "Exception encountered: " & ex.Message & vbCrLf End Try End Sub
5. Add Play To code
The code in this step is all that you need to enable Play To in your application. It gets a reference to the PlayToManager for the current application and associates the event handler for the SourceRequested event. In the SourceRequested event handler, you pass the PlayToSource property of the media or image element to the SetSource method of the PlayToManager. The PlayToManager then streams the media to the Play To target selected by the user.
In the MainPage.xaml.cs or MainPage.xaml.vb file and add the following code after the code from the previous step.
private Windows.Media.PlayTo.PlayToManager ptm; protected override void OnNavigatedTo(NavigationEventArgs e) { ptm = Windows.Media.PlayTo.PlayToManager.GetForCurrentView(); ptm.SourceRequested += SourceRequested; ShowMedia("VideoPlayer"); LoadVideo(); } private Windows.UI.Core.CoreDispatcher dispatcher = Window.Current.CoreWindow.Dispatcher; async private void SourceRequested(Windows.Media.PlayTo.PlayToManager sender, Windows.Media.PlayTo.PlayToSourceRequestedEventArgs e) { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { try { Windows.Media.PlayTo.PlayToSourceRequest sr = e.SourceRequest; Windows.Media.PlayTo.PlayToSource controller = null; Windows.Media.PlayTo.PlayToSourceDeferral deferral = e.SourceRequest.GetDeferral(); try { if (mediaElement is Image) { controller = ((Image)mediaElement).PlayToSource; } else { controller = ((MediaElement)mediaElement).PlayToSource; } } catch (Exception ex) { MessageBlock.Text += "Exception encountered: " + ex.Message + "\n"; } sr.SetSource(controller); deferral.Complete(); } catch (Exception ex) { MessageBlock.Text += "Exception encountered: " + ex.Message + "\n"; } }); }
Private ptm As Windows.Media.PlayTo.PlayToManager Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs) ptm = Windows.Media.PlayTo.PlayToManager.GetForCurrentView() AddHandler ptm.SourceRequested, AddressOf SourceRequested ShowMedia("VideoPlayer") LoadVideo() End Sub Private dispatcher As Windows.UI.Core.CoreDispatcher = Window.Current.CoreWindow.Dispatcher Private Async Sub SourceRequested( sender As Windows.Media.PlayTo.PlayToManager, e As Windows.Media.PlayTo.PlayToSourceRequestedEventArgs) Await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Sub() Try Dim sr = e.SourceRequest Dim controller As Windows.Media.PlayTo.PlayToSource = Nothing Dim deferral = e.SourceRequest.GetDeferral() Try If TypeOf mediaElement Is Image Then controller = CType(mediaElement, Image).PlayToSource Else controller = CType(mediaElement, MediaElement).PlayToSource End If Catch ex As Exception MessageBlock.Text &= "Exception encountered: " & ex.Message & vbCrLf End Try sr.SetSource(controller) deferral.Complete() Catch ex As Exception MessageBlock.Text &= "Exception encountered: " & ex.Message & vbCrLf End Try End Sub) End Sub
6. Create a Play To target (optional)
To run the application, you need a target device to which Play To can stream media. If you do not have a certified Play To receiver, you can use Windows Media Player as a target device. To use Windows Media Player as a target device, your computer must be connected to a private network.
- Start Windows Media Player.
- Expand the Stream menu and enable the Allow remote control of my Player... option. Leave Windows Media Player open, because it must be running to be available as a Play To target.
- Open the Devices and Printers control panel. Click Add devices and printers. In the Add devices and printers wizard, in the Choose a device or printer to add to this PC window, locate the Digital media renderer for your PC. This is the Windows Media Player for your PC. Select it and click Next. When the wizard finishes, you will see your instance of Windows Media Player in the list of Multimedia Devices.
7. Run the application
- In Visual Studio, press F5 (debug) to run the application. You can select any of the media buttons to play or view the first media item in the various media libraries. To stream the media to the target device while the media is playing, open the Devices charm and select your Play To target.
Summary
In this quickstart, you added Play To capability to an application that played video and audio content and displayed images. The Play To capability enables users to stream content from the application to a certified Play To receiver available on their network.
Related topics
Streaming media to devices using Play To
Samples