Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Quickstart: Using Play To in applications (XAML)

Applies to Windows only

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:

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

  1. 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.
  2. 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();
    }
    
    
    

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";
        }
    }
    
    
    

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";
            }
        });
    }
    
    
    

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.

  1. Start Windows Media Player.
  2. 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.
  3. 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
Play To sample
PlayToReceiver sample
Media Server sample

 

 

Show:
© 2014 Microsoft