PlayToSource PlayToSource PlayToSource PlayToSource Class

Represents a media element to connect to a Play To target.

Syntax

Declaration

public sealed class PlayToSourcepublic sealed class PlayToSourcePublic NotInheritable Class PlayToSourcepublic sealed class PlayToSource

Remarks

For an example of using the PlayToSource class, see Streaming a slide show using Play To (JavaScript) or Media casting.

Examples

IReadOnlyList<Windows.Storage.StorageFile> imageList;   // contains the list of images to show
bool streaming = false;      // true when streaming using Play To; otherwise false
int timeLapse = 5;           // time between images (5 seconds)
int imageSize = 600;         // size of current displayed image
int thumbnailSize = 200;     // size of "thumbnail" of next image
int currentImage = 0;        // index of the current image from imageList

// Get the list of images from the Pictures folder and start the slide show.
async private void StartSlideShow()
{
    var resultsLibrary = await
        Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
    imageList = resultsLibrary;
    if (imageList.Count > 0)
    {
        var image = QueueImage(0, true);
    }
    else
    {
        MessageBlock.Text = "There are no images in the Pictures library.";
    }
}

// PlayNextImage
// Called when a new image is displayed due to a timeout.
// Removes the current image object and queues a new next image.
// Sets the next image index as the new current image, and increases the size 
// of the new current image. Then sets the timeout to display the next image.

private async void PlayNextImage(int num)
{
    // Stop the timer to avoid repeating.
    if (timer != null) { timer.Stop(); }

    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        async () =>
        {
            SlideShowPanel.Children.Remove((UIElement)(SlideShowPanel.FindName("image" + num)));
            var i = await QueueImage(num + 2, false);

            currentImage = num + 1;
            ((Image)SlideShowPanel.FindName("image" + currentImage)).Width = imageSize;
        });

    timer = new Windows.UI.Xaml.DispatcherTimer();
    timer.Interval = new TimeSpan(0, 0, timeLapse);
    timer.Tick += delegate(object sender, object e)
    {
        PlayNextImage(num + 1);
    };
    timer.Start();
}

// QueueImage
// Called to create an image object for the displayed images.

private async System.Threading.Tasks.Task<Image> QueueImage(int num, bool isFirstImage)
{
    // Create the image element for the specified image index and add to the
    // slide show div.

    Image image = new Image();
    image.Width = isFirstImage ? imageSize : thumbnailSize;
    image.Name = "image" + num;
    image.VerticalAlignment = VerticalAlignment.Bottom;
    var fileContents = await imageList[num % imageList.Count].OpenReadAsync();
    var imageBitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
    imageBitmap.SetSource(fileContents);
    image.Source = imageBitmap;

    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        () =>
        {
            SlideShowPanel.Children.Add(image);
        });

    // If this is the first image of the slide show, queue the next image. Do
    // not queue if streaming as images are already queued before
    // streaming using Play To.

    if (isFirstImage && !streaming)
    {
        var i = await QueueImage(num + 1, false);

        timer = new Windows.UI.Xaml.DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, timeLapse);
        timer.Tick += delegate(object sender, object e)
        {
            PlayNextImage(num);
        };
        timer.Start();
    }

    // Use the transferred event of the Play To connection for the current image object
    // to "move" to the next image in the slide show. The transferred event occurs
    // when the PlayToSource.playNext() method is called, or when the Play To
    // Receiver selects the next image.

    image.PlayToSource.Connection.Transferred += 
        async delegate(Windows.Media.PlayTo.PlayToConnection sender, 
                 Windows.Media.PlayTo.PlayToConnectionTransferredEventArgs e)
           { 
               currentImage = num + 1;

               await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                   () =>
                   {
                       ((Image)SlideShowPanel.FindName("image" + currentImage)).Width = imageSize;
                   });
           };


// Use the statechanged event to determine which action to take or to respond
// if the Play To Receiver is disconnected.
image.PlayToSource.Connection.StateChanged += 
    async delegate(Windows.Media.PlayTo.PlayToConnection sender,
             Windows.Media.PlayTo.PlayToConnectionStateChangedEventArgs e)
    {
        switch (e.CurrentState) {
            case Windows.Media.PlayTo.PlayToConnectionState.Disconnected:

                // If the state is disconnected and the current image index equals the 
                // num value passed to queueImage, then the image element is not connected 
                // to the Play To Receiver any more. Restart the slide show.
                // Otherwise, the current image has been discarded and the slide show
                // has moved to the next image. Clear the current image object and
                // remove it from the slide show div.

                if (currentImage == num)
                {
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, 
                        async () =>
                        {
                            MessageBlock.Text = "Slideshow disconnected";

                            // Cancel any existing timeout
                            if (timer != null) { timer.Stop(); }

                            // Clear all image objects from the slide show div
                            SlideShowPanel.Children.Clear();

                            // Reset the slide show objects and values to their beginning state
                            streaming = false;
                            DisconnectButton.Visibility = Visibility.Collapsed;
                            InstructionsBlock.Visibility = Visibility.Visible;
                            DisconnectButton.Click -= DisconnectButtonClick;

                            // Restart the slide show from the current image index
                            var i = await QueueImage(currentImage, true);
                        });
                } 
                else 
                { 
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                            () =>
                            {
                                image.PlayToSource.Next = null;

                                if (streaming)
                                {
                                    SlideShowPanel.Children.Remove(image);
                                }   
                            });
                }

                break;
            
            case Windows.Media.PlayTo.PlayToConnectionState.Connected:

                // If the state is connected and the previous state is disconnected, 
                // then the image element is newly connected. Queue up the next image so 
                // that it is loaded while the current image is being displayed.
                // If the previous state is rendering, then the user has paused the slideshow 
                // on the Play To Receiver. Clear the current timeout until the user restarts
                // the slide show.
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                    async () =>
                    {
                        if (e.PreviousState ==  Windows.Media.PlayTo.PlayToConnectionState.Disconnected)
                        {
                            var imageNext = await QueueImage(num + 1, false);
                            image.PlayToSource.Next = imageNext.PlayToSource;
                        } 
                        else if (e.PreviousState == Windows.Media.PlayTo.PlayToConnectionState.Rendering) 
                        {
                            if (timer != null) { timer.Stop(); }
                        }

                        if (currentImage == num) 
                        {
                            MessageBlock.Text = "Slideshow connected";
                        }
                    });
                break;

            case  Windows.Media.PlayTo.PlayToConnectionState.Rendering:

                // If the state is rendering and the previous state is
                // connected, then the Play To Receiver has restarted
                // the slide show.
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                        () =>
                        {
                            if (e.PreviousState == Windows.Media.PlayTo.PlayToConnectionState.Connected)
                            {
                                // Clear any existing timeout.
                                if (timer != null) { timer.Stop(); }

                                // Restart the slide show.
                                timer = new Windows.UI.Xaml.DispatcherTimer();
                                timer.Interval = new TimeSpan(0, 0, timeLapse);
                                timer.Tick += delegate(object s, object args)
                                {
                                    image.PlayToSource.PlayNext();
                                };
                                timer.Start();
                            }

                            if (currentImage == num)
                            {
                                MessageBlock.Text = "Slideshow rendering";
                            }
                       }); 
                break;
            }
        };

    return image;
}
var states = Windows.Media.PlayTo.PlayToConnectionState, // alias for PlayToConnectionState
    imageList,               // contains the list of images to show
    streaming = false,       // true when streaming using Play To; otherwise false
    cancel = 0,              // used to cancel a timeout
    timeLapse = 5,           // time between images (5 seconds)
    imageSize = "600px",     // size of current displayed image
    thumbnailSize = "200px", // size of "thumbnail" of next image
    currentImage = 0;        // index of the current image from imageList

// Get the list of images from the Pictures folder and start the slide show.

function startSlideShow() {
    Windows.Storage.KnownFolders.picturesLibrary.getFilesAsync().then(
        function (resultsLibrary) {
            imageList = resultsLibrary;
            if (imageList.length > 0) {
                var image = queueImage(0, true);
            } else {
                id("messageDiv").innerHTML = "There are no images in the Pictures library.";
            }
        });
}


// playNextImage
// Called when a new image is displayed due to a timeout.
// Removes the current image object and queues a new next image.
// Sets the next image index as the new current image, and increases the size 
// of the new current image. Then sets the timeout to display the next image.

function playNextImage(num) {
    id("slideshowDiv").removeChild(id("image" + num));
    queueImage(num + 2, false);

    currentImage = num + 1;
    id("image" + currentImage).style.width = imageSize;

    cancel = setTimeout(function () {
        playNextImage(num + 1);
    }, timeLapse * 1000);
}


// queueImage
// Called to create an image object for the displayed images.

function queueImage(num, isFirstImage) {

    // Create the image element for the specified image index and add to the
    // slide show div.

    var image = document.createElement("img");
    image.style.width = (isFirstImage ? imageSize : thumbnailSize);
    image.id = "image" + num;
    image.src = URL.createObjectURL(imageList[num % imageList.length], { oneTimeOnly: true });
    id("slideshowDiv").appendChild(image);

    // If this is the first image of the slide show, queue the next image. Do
    // not queue if streaming as images are already queued before
    // streaming using Play To.

    if (isFirstImage && !streaming) {

        queueImage(num + 1, false);

        cancel = setTimeout(function () {
            playNextImage(num);
        }, timeLapse * 1000);            
    }

    // Use the transferred event of the Play To connection for the current image object
    // to "move" to the next image in the slide show. The transferred event occurs
    // when the PlayToSource.playNext() method is called, or when the Play To
    // Receiver selects the next image.

    image.msPlayToSource.connection.addEventListener("transferred", function () {

        currentImage = num + 1;
        id("image" + currentImage).style.width = imageSize;

    }, false);


    // Use the statechanged event to determine which action to take or to respond
    // if the Play To Receiver is disconnected.
    image.msPlayToSource.connection.addEventListener("statechanged", function (e) {

        switch (e.currentState) {
            case states.disconnected:

                // If the state is disconnected and the current image index equals the 
                // num value passed to queueImage, then the image element is not connected 
                // to the Play To Receiver any more. Restart the slide show.
                // Otherwise, the current image has been discarded and the slide show
                // has moved to the next image. Clear the current image object and
                // remove it from the slide show div.

                if (currentImage == num) {
                    id("messageDiv").innerHTML = "Slideshow disconnected";

                    // Cancel any existing timeout
                    if (cancel) {
                        clearTimeout(cancel);
                    }

                    // Clear all image objects from the slide show div
                    while (id("slideshowDiv").firstChild) {
                        id("slideshowDiv").removeChild(id("slideshowDiv").firstChild);
                    }

                    // Reset the slide show objects and values to their beginning state
                    streaming = false;
                    id("disconnectButton").style.display = "none";
                    id("instructionsDiv").style.display = "block";
                    disconnectButton.removeEventListener("click", disconnectButtonClick, false);

                    // Restart the slide show from the current image index
                    queueImage(currentImage, true);
                } else {
                    image.msPlayToSource.next = null;
                    image.removeAttribute("src");

                    if (streaming) {
                        id("slideshowDiv").removeChild(image);
                    }
                }

                break;
                
            case states.connected:

                // If the state is connected and the previous state is disconnected, 
                // then the image element is newly connected. Queue up the next image so 
                // that it is loaded while the current image is being displayed.
                // If the previous state is rendering, then the user has paused the slideshow 
                // on the Play To Receiver. Clear the current timeout until the user restarts
                // the slide show.

                if (e.previousState === states.disconnected) {
                    var imageNext = queueImage(num + 1, false);
                    image.msPlayToSource.next = imageNext.msPlayToSource;
                } else if (e.previousState === states.rendering) {
                    if (cancel) {
                        clearTimeout(cancel);
                        cancel = 0;
                    }
                }

                if (currentImage == num) {
                    id("messageDiv").innerHTML = "Slideshow connected";
                }

                break;

            case states.rendering:

                // If the state is rendering and the previous state is
                // connected, then the Play To Receiver has restarted
                // the slide show.

                if (e.previousState === states.connected) {

                    // Clear any existing timeout.
                    if (cancel) {
                        clearTimeout(cancel);
                    }

                    // Restart the slide show.
                    cancel = setTimeout(function () {
                        image.msPlayToSource.playNext();
                    }, timeLapse * 1000);
                }

                if (currentImage == num) {
                    id("messageDiv").innerHTML = "Slideshow rendering";
                }

                break;
        }

    }, false);

    return image;
}
Private imageList As IReadOnlyList(Of Windows.Storage.StorageFile)    ' contains the list of images to show
Private streaming As Boolean = False       ' true when streaming using Play To otherwise false
Private timeLapse As Integer = 5           ' time between images (5 seconds)
Private imageSize As Integer = 600         ' size of current displayed image
Private thumbnailSize As Integer = 200     ' size of "thumbnail" of next image
Private currentImage As Integer = 0        ' index of the current image from imageList

' Get the list of images from the Pictures folder and start the slide show.
Private Async Sub StartSlideShow()
    Dim resultsLibrary =
        Await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync()
    imageList = resultsLibrary
    If (imageList.Count > 0) Then
        Dim image = QueueImage(0, True)
    Else
        MessageBlock.Text = "There are no images in the Pictures library."
    End If
End Sub

' PlayNextImage
' Called when a new image is displayed due to a timeout.
' Removes the current image object and queues a new next image.
' Sets the next image index as the new current image, and increases the size 
' of the new current image. Then sets the timeout to display the next image.

Private Async Sub PlayNextImage(num As Integer)
    ' Stop the timer to avoid repeating.
    If timer IsNot Nothing Then timer.Stop()

    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        Async Sub()
            SlideShowPanel.Children.Remove(CType(SlideShowPanel.FindName("image" & num), UIElement))
            Dim i = Await QueueImage(num + 2, False)

            currentImage = num + 1
            CType(SlideShowPanel.FindName("image" & currentImage), Image).Width = imageSize
        End Sub)

    timer = New Windows.UI.Xaml.DispatcherTimer()
    timer.Interval = New TimeSpan(0, 0, timeLapse)
    AddHandler timer.Tick, Sub(sender As Object, e As Object)
                               PlayNextImage(num + 1)
                           End Sub
    timer.Start()
End Sub

' QueueImage
' Called to create an image object for the displayed images.

Private Async Function QueueImage(num As Integer, isFirstImage As Boolean) As Task(Of Image)
    ' Create the image element for the specified image index and add to the
    ' slide show div.

    Dim image = New Image()
    image.Width = If(isFirstImage, imageSize, thumbnailSize)
    image.Name = "image" & num
    image.VerticalAlignment = VerticalAlignment.Bottom
    Dim fileContents = Await imageList(num Mod imageList.Count).OpenReadAsync()
    Dim imageBitmap = New BitmapImage()
    imageBitmap.SetSource(fileContents)
    image.Source = imageBitmap

    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        Sub()
            SlideShowPanel.Children.Add(image)
        End Sub)

    ' If this is the first image of the slide show, queue the next image. Do
    ' not queue if streaming as images are already queued before
    ' streaming using Play To.

    If isFirstImage AndAlso Not streaming Then

        Dim i = Await QueueImage(num + 1, False)

        timer = New Windows.UI.Xaml.DispatcherTimer()
        timer.Interval = New TimeSpan(0, 0, timeLapse)
        AddHandler timer.Tick, Sub(sender As Object, e As Object)
                                   PlayNextImage(num)
                               End Sub
        timer.Start()
    End If

' Use the transferred event of the Play To connection for the current image object
' to "move" to the next image in the slide show. The transferred event occurs
' when the PlayToSource.playNext() method is called, or when the Play To
' Receiver selects the next image.

    AddHandler image.PlayToSource.Connection.Transferred,
        Async Sub(sender As Windows.Media.PlayTo.PlayToConnection,
                  e As Windows.Media.PlayTo.PlayToConnectionTransferredEventArgs)

            currentImage = num + 1

            Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                Sub()
                    CType(SlideShowPanel.FindName("image" & currentImage), Image).Width = imageSize
                End Sub)
        End Sub


    ' Use the statechanged event to determine which action to take or to respond
    ' if the Play To Receiver is disconnected.
    AddHandler image.PlayToSource.Connection.StateChanged,
        Async Sub(sender As Windows.Media.PlayTo.PlayToConnection,
                  e As Windows.Media.PlayTo.PlayToConnectionStateChangedEventArgs)

            Select Case e.CurrentState
                Case Windows.Media.PlayTo.PlayToConnectionState.Disconnected

                    ' If the state is disconnected and the current image index equals the 
                    ' num value passed to queueImage, then the image element is not connected 
                    ' to the Play To Receiver any more. Restart the slide show.
                    ' Otherwise, the current image has been discarded and the slide show
                    ' has moved to the next image. Clear the current image object and
                    ' remove it from the slide show div.

                    If currentImage = num Then
                        Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                            Async Sub()
                                MessageBlock.Text = "Slideshow disconnected"

                                ' Cancel any existing timeout
                                If timer IsNot Nothing Then timer.Stop()

                                ' Clear all image objects from the slide show div
                                SlideShowPanel.Children.Clear()

                                ' Reset the slide show objects and values to their beginning state
                                streaming = False
                                DisconnectButton.Visibility = Visibility.Collapsed
                                InstructionsBlock.Visibility = Visibility.Visible
                                AddHandler DisconnectButton.Click, AddressOf DisconnectButtonClick

                                ' Restart the slide show from the current image index
                                Dim i = Await QueueImage(currentImage, True)
                            End Sub)
                    Else 
                           Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                Sub()
                                    image.PlayToSource.Next = Nothing

                                    If streaming Then
                                        SlideShowPanel.Children.Remove(image)
                                    End If
                                End Sub)
                    End If

                Case Windows.Media.PlayTo.PlayToConnectionState.Connected

                ' If the state is connected and the previous state is disconnected, 
                ' then the image element is newly connected. Queue up the next image so 
                ' that it is loaded while the current image is being displayed.
                ' If the previous state is rendering, then the user has paused the slideshow 
                ' on the Play To Receiver. Clear the current timeout until the user restarts
                ' the slide show.
                Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                    Async Sub()
                            If e.PreviousState = Windows.Media.PlayTo.PlayToConnectionState.Disconnected Then
                                Dim imageNext = Await QueueImage(num + 1, False)
                                image.PlayToSource.Next = imageNext.PlayToSource
                            ElseIf e.PreviousState = Windows.Media.PlayTo.PlayToConnectionState.Rendering Then
                                If timer IsNot Nothing Then timer.Stop()
                            End If

                            If currentImage = num Then
                                MessageBlock.Text = "Slideshow connected"

                            End If
                        End Sub)

                Case Windows.Media.PlayTo.PlayToConnectionState.Rendering

                ' If the state is rendering and the previous state is
                ' connected, then the Play To Receiver has restarted
                ' the slide show.
                Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                   Sub()
                           If e.PreviousState = Windows.Media.PlayTo.PlayToConnectionState.Connected Then

                               ' Clear any existing timeout.
                               If timer IsNot Nothing Then timer.Stop()

                               ' Restart the slide show.
                               timer = New Windows.UI.Xaml.DispatcherTimer()
                               timer.Interval = New TimeSpan(0, 0, timeLapse)
                               AddHandler timer.Tick, Sub(s As Object, args As Object)
                                                          image.PlayToSource.PlayNext()
                                                      End Sub
                               timer.Start()
                           End If

                           If currentImage = num Then
                               MessageBlock.Text = "Slideshow rendering"
                           End If
                       End Sub)
            End Select
            End Function

    Return image
End Function
// Set up the Play To contract.

// Used to pass an image to Play To that will not be removed/destroyed
// by the slide show logic. For example, if the user opens the Devices
// charm and the sourcerequested event fires, but the image display timeout
// completes before the user selects a target device, then the image that
// was being displayed is removed and destroyed. intialImage is never 
// destroyed so Play To will always have a valid source to stream.
Image initialImage = null;

private async void SourceRequested(Windows.Media.PlayTo.PlayToManager sender, 
                             Windows.Media.PlayTo.PlayToSourceRequestedEventArgs e)
{
    var deferral = e.SourceRequest.GetDeferral();

    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
    () =>
    {
        initialImage = new Image();

        // Use the statechanged event of the image passed to Play To to determine when
        // the image is finally connected to the Play To Receiver.
        initialImage.PlayToSource.Connection.StateChanged += InitialImageConnectionStateChanged;

        // Provide Play To with the first image to stream.
        e.SourceRequest.SetSource(initialImage.PlayToSource);

        deferral.Complete();
    });
}

private async void InitialImageConnectionStateChanged(Windows.Media.PlayTo.PlayToConnection sender,
                                                      Windows.Media.PlayTo.PlayToConnectionStateChangedEventArgs e)
{
        if (e.CurrentState == Windows.Media.PlayTo.PlayToConnectionState.Connected) {

            await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, 
                async () =>
                {
                    // Clear any existing timeout.
                    if (timer != null) { timer.Stop(); }

                    // Clear the slide show panel.
                    SlideShowPanel.Children.Clear();

                    // Set the slide show objects and values to show that we are streaming.
                    streaming = true;
                    DisconnectButton.Visibility = Visibility.Visible;
                    InstructionsBlock.Visibility = Visibility.Collapsed;

                    // Queue and display the next image.
                    var image = await QueueImage(currentImage, true);
                    initialImage.PlayToSource.Next = image.PlayToSource;
                    initialImage.PlayToSource.PlayNext();
                });
        };
}

// Update the once the user has selected a device to stream to.

private async void SourceSelected(Windows.Media.PlayTo.PlayToManager sender, 
                            Windows.Media.PlayTo.PlayToSourceSelectedEventArgs e)
{
    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        () =>
        {
            DisconnectButton.Click += DisconnectButtonClick;
            MessageBlock.Text = "Streaming to " + e.FriendlyName + "...";
            DeviceBlock.Text = e.FriendlyName + ".\nClick here to disconnect.";
            var imageBitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
            imageBitmap.SetSource(e.Icon);
            IconImage.Source = imageBitmap;
        });
}

private void DisconnectButtonClick(object sender, RoutedEventArgs e)
{
    Windows.Media.PlayTo.PlayToManager.ShowPlayToUI();
}
// Set up the Play To contract.

// Used to pass an image to Play To that will not be removed/destroyed
// by the slide show logic. For example, if the user opens the Devices
// charm and the sourcerequested event fires, but the image display timeout
// completes before the user selects a target device, then the image that
// was being displayed is removed and destroyed. intialImage is never 
// destroyed so Play To will always have a valid source to stream.
var initialImage = null;

var ptm = Windows.Media.PlayTo.PlayToManager.getForCurrentView();

ptm.addEventListener("sourcerequested", function (e) {
    initialImage = document.createElement("img");

    // Use the statechanged event of the image passed to Play To to determine when
    // the image is finally connected to the Play To Receiver.
    initialImage.msPlayToSource.connection.addEventListener("statechanged", function (e) {

        if (e.currentState === states.connected) {

            // Clear any existing timeout.
            if (cancel) {
                clearTimeout(cancel);
                cancel = 0;
            }

            // Clear the slide show div.
            while (id("slideshowDiv").firstChild) {
                id("slideshowDiv").removeChild(id("slideshowDiv").firstChild);
            }

            // Set the slide show objects and values to show that we are streaming.
            streaming = true;
            id("disconnectButton").style.display = "block";
            id("instructionsDiv").style.display = "none";

            // Queue and display the next image.
            var image = queueImage(currentImage, true);
            initialImage.msPlayToSource.next = image.msPlayToSource;
            initialImage.msPlayToSource.playNext();
        }
    }, false);

    // Provide Play To with the first image to stream.
    e.sourceRequest.setSource(initialImage.msPlayToSource);

}, false);

// Update the once the user has selected a device to stream to.
ptm.addEventListener("sourceselected", function (e) {
    disconnectButton.addEventListener("click", disconnectButtonClick, false);
    id("messageDiv").innerHTML = "Streaming to " + e.friendlyName + "...";
    id("deviceSpan").innerHTML = e.friendlyName + ".<br/>Click here to disconnect.";
    id("iconImage").src = URL.createObjectURL(e.icon, { oneTimeOnly: true });
}, false);
' Set up the Play To contract.

' Used to pass an image to Play To that will not be removed/destroyed
' by the slide show logic. For example, if the user opens the Devices
' charm and the sourcerequested event fires, but the image display timeout
' completes before the user selects a target device, then the image that
' was being displayed is removed and destroyed. intialImage is never 
' destroyed so Play To will always have a valid source to stream.
Private initialImage As Image = Nothing

Private Async Sub SourceRequested(sender As Windows.Media.PlayTo.PlayToManager,
                             e As Windows.Media.PlayTo.PlayToSourceRequestedEventArgs)

    Dim deferral = e.SourceRequest.GetDeferral()

    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
    Sub()
        initialImage = New Image()

        ' Use the statechanged event of the image passed to Play To to determine when
        ' the image is finally connected to the Play To Receiver.
        AddHandler initialImage.PlayToSource.Connection.StateChanged, AddressOf InitialImageConnectionStateChanged

        ' Provide Play To with the first image to stream.
        e.SourceRequest.SetSource(initialImage.PlayToSource)

        deferral.Complete()
    End Sub)
End Sub

Private Async Sub InitialImageConnectionStateChanged(sender As Windows.Media.PlayTo.PlayToConnection,
                                                         e As Windows.Media.PlayTo.PlayToConnectionStateChangedEventArgs)

    If e.CurrentState = Windows.Media.PlayTo.PlayToConnectionState.Connected Then

        Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            Async Sub()
                ' Clear any existing timeout.
                If timer IsNot Nothing Then timer.Stop()

                ' Clear the slide show panel.
                SlideShowPanel.Children.Clear()

                ' Set the slide show objects and values to show that we are streaming.
                streaming = True
                DisconnectButton.Visibility = Visibility.Visible
                InstructionsBlock.Visibility = Visibility.Collapsed

                ' Queue and display the next image.
                Dim image = Await QueueImage(currentImage, True)
                initialImage.PlayToSource.Next = image.PlayToSource
                initialImage.PlayToSource.PlayNext()
            End Sub)
    End If
End Sub

' Update the once the user has selected a device to stream to.

Private Async Sub SourceSelected(sender As Windows.Media.PlayTo.PlayToManager,
                                 e As Windows.Media.PlayTo.PlayToSourceSelectedEventArgs)

    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        Sub()
            AddHandler DisconnectButton.Click, AddressOf DisconnectButtonClick
            MessageBlock.Text = "Streaming to " & e.FriendlyName & "..."
            DeviceBlock.Text = e.FriendlyName & "." & vbCr & "Click here to disconnect."
            Dim imageBitmap = New Windows.UI.Xaml.Media.Imaging.BitmapImage()
            imageBitmap.SetSource(e.Icon)
            IconImage.Source = imageBitmap
        End Sub)
End Sub

Private Sub DisconnectButtonClick()
    Windows.Media.PlayTo.PlayToManager.ShowPlayToUI()
End Sub

Properties summary

Gets the connection to the Play To target.

Gets or sets the next Play To source element.

Specifies a preferred Uniform Resource Identifier (URI) for the media stream, such as a cloud based media server, used is used for Play To by reference.

Methods summary

Connects the next Play To source element to the Play To target.

Properties

  • Connection
    Connection
    Connection
    Connection

    Gets the connection to the Play To target.

    public PlayToConnection Connection { get; }public PlayToConnection Connection { get; }Public ReadOnly Property Connection As PlayToConnectionpublic PlayToConnection Connection { get; }

    Property Value

  • Next
    Next
    Next
    Next

    Gets or sets the next Play To source element.

    public PlayToSource Next { get; set; }public PlayToSource Next { get; set; }Public ReadWrite Property Next As PlayToSourcepublic PlayToSource Next { get; set; }

    Property Value

    Remarks

    For an example of using the Next property, see Streaming a slide show using Play To (JavaScript) or Media casting.

    Examples

    // Set up the Play To contract.
    
    // Used to pass an image to Play To that will not be removed/destroyed
    // by the slide show logic. For example, if the user opens the Devices
    // charm and the sourcerequested event fires, but the image display timeout
    // completes before the user selects a target device, then the image that
    // was being displayed is removed and destroyed. intialImage is never 
    // destroyed so Play To will always have a valid source to stream.
    Image initialImage = null;
    
    private async void SourceRequested(Windows.Media.PlayTo.PlayToManager sender, 
                                 Windows.Media.PlayTo.PlayToSourceRequestedEventArgs e)
    {
        var deferral = e.SourceRequest.GetDeferral();
    
        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        () =>
        {
            initialImage = new Image();
    
            // Use the statechanged event of the image passed to Play To to determine when
            // the image is finally connected to the Play To Receiver.
            initialImage.PlayToSource.Connection.StateChanged += InitialImageConnectionStateChanged;
    
            // Provide Play To with the first image to stream.
            e.SourceRequest.SetSource(initialImage.PlayToSource);
    
            deferral.Complete();
        });
    }
    
    private async void InitialImageConnectionStateChanged(Windows.Media.PlayTo.PlayToConnection sender,
                                                          Windows.Media.PlayTo.PlayToConnectionStateChangedEventArgs e)
    {
            if (e.CurrentState == Windows.Media.PlayTo.PlayToConnectionState.Connected) {
    
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, 
                    async () =>
                    {
                        // Clear any existing timeout.
                        if (timer != null) { timer.Stop(); }
    
                        // Clear the slide show panel.
                        SlideShowPanel.Children.Clear();
    
                        // Set the slide show objects and values to show that we are streaming.
                        streaming = true;
                        DisconnectButton.Visibility = Visibility.Visible;
                        InstructionsBlock.Visibility = Visibility.Collapsed;
    
                        // Queue and display the next image.
                        var image = await QueueImage(currentImage, true);
                        initialImage.PlayToSource.Next = image.PlayToSource;
                        initialImage.PlayToSource.PlayNext();
                    });
            };
    }
    
    // Update the once the user has selected a device to stream to.
    
    private async void SourceSelected(Windows.Media.PlayTo.PlayToManager sender, 
                                Windows.Media.PlayTo.PlayToSourceSelectedEventArgs e)
    {
        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            () =>
            {
                DisconnectButton.Click += DisconnectButtonClick;
                MessageBlock.Text = "Streaming to " + e.FriendlyName + "...";
                DeviceBlock.Text = e.FriendlyName + ".\nClick here to disconnect.";
                var imageBitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
                imageBitmap.SetSource(e.Icon);
                IconImage.Source = imageBitmap;
            });
    }
    
    private void DisconnectButtonClick(object sender, RoutedEventArgs e)
    {
        Windows.Media.PlayTo.PlayToManager.ShowPlayToUI();
    }
    
    // Set up the Play To contract.
    
    // Used to pass an image to Play To that will not be removed/destroyed
    // by the slide show logic. For example, if the user opens the Devices
    // charm and the sourcerequested event fires, but the image display timeout
    // completes before the user selects a target device, then the image that
    // was being displayed is removed and destroyed. intialImage is never 
    // destroyed so Play To will always have a valid source to stream.
    var initialImage = null;
    
    var ptm = Windows.Media.PlayTo.PlayToManager.getForCurrentView();
    
    ptm.addEventListener("sourcerequested", function (e) {
        initialImage = document.createElement("img");
    
        // Use the statechanged event of the image passed to Play To to determine when
        // the image is finally connected to the Play To Receiver.
        initialImage.msPlayToSource.connection.addEventListener("statechanged", function (e) {
    
            if (e.currentState === states.connected) {
    
                // Clear any existing timeout.
                if (cancel) {
                    clearTimeout(cancel);
                    cancel = 0;
                }
    
                // Clear the slide show div.
                while (id("slideshowDiv").firstChild) {
                    id("slideshowDiv").removeChild(id("slideshowDiv").firstChild);
                }
    
                // Set the slide show objects and values to show that we are streaming.
                streaming = true;
                id("disconnectButton").style.display = "block";
                id("instructionsDiv").style.display = "none";
    
                // Queue and display the next image.
                var image = queueImage(currentImage, true);
                initialImage.msPlayToSource.next = image.msPlayToSource;
                initialImage.msPlayToSource.playNext();
            }
        }, false);
    
        // Provide Play To with the first image to stream.
        e.sourceRequest.setSource(initialImage.msPlayToSource);
    
    }, false);
    
    // Update the once the user has selected a device to stream to.
    ptm.addEventListener("sourceselected", function (e) {
        disconnectButton.addEventListener("click", disconnectButtonClick, false);
        id("messageDiv").innerHTML = "Streaming to " + e.friendlyName + "...";
        id("deviceSpan").innerHTML = e.friendlyName + ".<br/>Click here to disconnect.";
        id("iconImage").src = URL.createObjectURL(e.icon, { oneTimeOnly: true });
    }, false);
    
    ' Set up the Play To contract.
    
    ' Used to pass an image to Play To that will not be removed/destroyed
    ' by the slide show logic. For example, if the user opens the Devices
    ' charm and the sourcerequested event fires, but the image display timeout
    ' completes before the user selects a target device, then the image that
    ' was being displayed is removed and destroyed. intialImage is never 
    ' destroyed so Play To will always have a valid source to stream.
    Private initialImage As Image = Nothing
    
    Private Async Sub SourceRequested(sender As Windows.Media.PlayTo.PlayToManager,
                                 e As Windows.Media.PlayTo.PlayToSourceRequestedEventArgs)
    
        Dim deferral = e.SourceRequest.GetDeferral()
    
        Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        Sub()
            initialImage = New Image()
    
            ' Use the statechanged event of the image passed to Play To to determine when
            ' the image is finally connected to the Play To Receiver.
            AddHandler initialImage.PlayToSource.Connection.StateChanged, AddressOf InitialImageConnectionStateChanged
    
            ' Provide Play To with the first image to stream.
            e.SourceRequest.SetSource(initialImage.PlayToSource)
    
            deferral.Complete()
        End Sub)
    End Sub
    
    Private Async Sub InitialImageConnectionStateChanged(sender As Windows.Media.PlayTo.PlayToConnection,
                                                             e As Windows.Media.PlayTo.PlayToConnectionStateChangedEventArgs)
    
        If e.CurrentState = Windows.Media.PlayTo.PlayToConnectionState.Connected Then
    
            Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                Async Sub()
                    ' Clear any existing timeout.
                    If timer IsNot Nothing Then timer.Stop()
    
                    ' Clear the slide show panel.
                    SlideShowPanel.Children.Clear()
    
                    ' Set the slide show objects and values to show that we are streaming.
                    streaming = True
                    DisconnectButton.Visibility = Visibility.Visible
                    InstructionsBlock.Visibility = Visibility.Collapsed
    
                    ' Queue and display the next image.
                    Dim image = Await QueueImage(currentImage, True)
                    initialImage.PlayToSource.Next = image.PlayToSource
                    initialImage.PlayToSource.PlayNext()
                End Sub)
        End If
    End Sub
    
    ' Update the once the user has selected a device to stream to.
    
    Private Async Sub SourceSelected(sender As Windows.Media.PlayTo.PlayToManager,
                                     e As Windows.Media.PlayTo.PlayToSourceSelectedEventArgs)
    
        Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            Sub()
                AddHandler DisconnectButton.Click, AddressOf DisconnectButtonClick
                MessageBlock.Text = "Streaming to " & e.FriendlyName & "..."
                DeviceBlock.Text = e.FriendlyName & "." & vbCr & "Click here to disconnect."
                Dim imageBitmap = New Windows.UI.Xaml.Media.Imaging.BitmapImage()
                imageBitmap.SetSource(e.Icon)
                IconImage.Source = imageBitmap
            End Sub)
    End Sub
    
    Private Sub DisconnectButtonClick()
        Windows.Media.PlayTo.PlayToManager.ShowPlayToUI()
    End Sub
    
  • PreferredSourceUri
    PreferredSourceUri
    PreferredSourceUri
    PreferredSourceUri

    Specifies a preferred Uniform Resource Identifier (URI) for the media stream, such as a cloud based media server, used is used for Play To by reference.

    public Uri PreferredSourceUri { get; set; }public Uri PreferredSourceUri { get; set; }Public ReadWrite Property PreferredSourceUri As Uripublic Uri PreferredSourceUri { get; set; }

    Property Value

    • The preferred URI to stream the media from.

    Remarks

    Play To by reference enables web pages and Windows Store app to play Digital Rights Management (DRM) protected content. The app specifies a preferred Uniform Resource Identifier (URI) that will be sent to the PlayTo target device. This Uniform Resource Identifier (URI) can point to a cloud based media server. If the PreferredSourceUri is present, the PlayTo target device can stream content directly from the cloud, which can be Digital Rights Management (DRM) protected, instead of streaming content from the Windows 8.1 machine which must be unprotected content.

Methods

  • PlayNext()
    PlayNext()
    PlayNext()
    PlayNext()

    Connects the next Play To source element to the Play To target.

    public void PlayNext()public void PlayNext()Public Function PlayNext() As voidpublic void PlayNext()

    Remarks

    You can use the PlayNext() method to stop streaming the current Play To source media to the target and then start streaming the Play To source identified by the Next property to the Play To target.

    For an example of using the Next property, see Streaming a slide show using Play To (JavaScript) or Media casting.

    Examples

    IReadOnlyList<Windows.Storage.StorageFile> imageList;   // contains the list of images to show
    bool streaming = false;      // true when streaming using Play To; otherwise false
    int timeLapse = 5;           // time between images (5 seconds)
    int imageSize = 600;         // size of current displayed image
    int thumbnailSize = 200;     // size of "thumbnail" of next image
    int currentImage = 0;        // index of the current image from imageList
    
    // Get the list of images from the Pictures folder and start the slide show.
    async private void StartSlideShow()
    {
        var resultsLibrary = await
            Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
        imageList = resultsLibrary;
        if (imageList.Count > 0)
        {
            var image = QueueImage(0, true);
        }
        else
        {
            MessageBlock.Text = "There are no images in the Pictures library.";
        }
    }
    
    // PlayNextImage
    // Called when a new image is displayed due to a timeout.
    // Removes the current image object and queues a new next image.
    // Sets the next image index as the new current image, and increases the size 
    // of the new current image. Then sets the timeout to display the next image.
    
    private async void PlayNextImage(int num)
    {
        // Stop the timer to avoid repeating.
        if (timer != null) { timer.Stop(); }
    
        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            async () =>
            {
                SlideShowPanel.Children.Remove((UIElement)(SlideShowPanel.FindName("image" + num)));
                var i = await QueueImage(num + 2, false);
    
                currentImage = num + 1;
                ((Image)SlideShowPanel.FindName("image" + currentImage)).Width = imageSize;
            });
    
        timer = new Windows.UI.Xaml.DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, timeLapse);
        timer.Tick += delegate(object sender, object e)
        {
            PlayNextImage(num + 1);
        };
        timer.Start();
    }
    
    // QueueImage
    // Called to create an image object for the displayed images.
    
    private async System.Threading.Tasks.Task<Image> QueueImage(int num, bool isFirstImage)
    {
        // Create the image element for the specified image index and add to the
        // slide show div.
    
        Image image = new Image();
        image.Width = isFirstImage ? imageSize : thumbnailSize;
        image.Name = "image" + num;
        image.VerticalAlignment = VerticalAlignment.Bottom;
        var fileContents = await imageList[num % imageList.Count].OpenReadAsync();
        var imageBitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
        imageBitmap.SetSource(fileContents);
        image.Source = imageBitmap;
    
        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            () =>
            {
                SlideShowPanel.Children.Add(image);
            });
    
        // If this is the first image of the slide show, queue the next image. Do
        // not queue if streaming as images are already queued before
        // streaming using Play To.
    
        if (isFirstImage && !streaming)
        {
            var i = await QueueImage(num + 1, false);
    
            timer = new Windows.UI.Xaml.DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, timeLapse);
            timer.Tick += delegate(object sender, object e)
            {
                PlayNextImage(num);
            };
            timer.Start();
        }
    
        // Use the transferred event of the Play To connection for the current image object
        // to "move" to the next image in the slide show. The transferred event occurs
        // when the PlayToSource.playNext() method is called, or when the Play To
        // Receiver selects the next image.
    
        image.PlayToSource.Connection.Transferred += 
            async delegate(Windows.Media.PlayTo.PlayToConnection sender, 
                     Windows.Media.PlayTo.PlayToConnectionTransferredEventArgs e)
               { 
                   currentImage = num + 1;
    
                   await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                       () =>
                       {
                           ((Image)SlideShowPanel.FindName("image" + currentImage)).Width = imageSize;
                       });
               };
    
    
    // Use the statechanged event to determine which action to take or to respond
    // if the Play To Receiver is disconnected.
    image.PlayToSource.Connection.StateChanged += 
        async delegate(Windows.Media.PlayTo.PlayToConnection sender,
                 Windows.Media.PlayTo.PlayToConnectionStateChangedEventArgs e)
        {
            switch (e.CurrentState) {
                case Windows.Media.PlayTo.PlayToConnectionState.Disconnected:
    
                    // If the state is disconnected and the current image index equals the 
                    // num value passed to queueImage, then the image element is not connected 
                    // to the Play To Receiver any more. Restart the slide show.
                    // Otherwise, the current image has been discarded and the slide show
                    // has moved to the next image. Clear the current image object and
                    // remove it from the slide show div.
    
                    if (currentImage == num)
                    {
                        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, 
                            async () =>
                            {
                                MessageBlock.Text = "Slideshow disconnected";
    
                                // Cancel any existing timeout
                                if (timer != null) { timer.Stop(); }
    
                                // Clear all image objects from the slide show div
                                SlideShowPanel.Children.Clear();
    
                                // Reset the slide show objects and values to their beginning state
                                streaming = false;
                                DisconnectButton.Visibility = Visibility.Collapsed;
                                InstructionsBlock.Visibility = Visibility.Visible;
                                DisconnectButton.Click -= DisconnectButtonClick;
    
                                // Restart the slide show from the current image index
                                var i = await QueueImage(currentImage, true);
                            });
                    } 
                    else 
                    { 
                        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                () =>
                                {
                                    image.PlayToSource.Next = null;
    
                                    if (streaming)
                                    {
                                        SlideShowPanel.Children.Remove(image);
                                    }   
                                });
                    }
    
                    break;
                
                case Windows.Media.PlayTo.PlayToConnectionState.Connected:
    
                    // If the state is connected and the previous state is disconnected, 
                    // then the image element is newly connected. Queue up the next image so 
                    // that it is loaded while the current image is being displayed.
                    // If the previous state is rendering, then the user has paused the slideshow 
                    // on the Play To Receiver. Clear the current timeout until the user restarts
                    // the slide show.
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                        async () =>
                        {
                            if (e.PreviousState ==  Windows.Media.PlayTo.PlayToConnectionState.Disconnected)
                            {
                                var imageNext = await QueueImage(num + 1, false);
                                image.PlayToSource.Next = imageNext.PlayToSource;
                            } 
                            else if (e.PreviousState == Windows.Media.PlayTo.PlayToConnectionState.Rendering) 
                            {
                                if (timer != null) { timer.Stop(); }
                            }
    
                            if (currentImage == num) 
                            {
                                MessageBlock.Text = "Slideshow connected";
                            }
                        });
                    break;
    
                case  Windows.Media.PlayTo.PlayToConnectionState.Rendering:
    
                    // If the state is rendering and the previous state is
                    // connected, then the Play To Receiver has restarted
                    // the slide show.
                        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                            () =>
                            {
                                if (e.PreviousState == Windows.Media.PlayTo.PlayToConnectionState.Connected)
                                {
                                    // Clear any existing timeout.
                                    if (timer != null) { timer.Stop(); }
    
                                    // Restart the slide show.
                                    timer = new Windows.UI.Xaml.DispatcherTimer();
                                    timer.Interval = new TimeSpan(0, 0, timeLapse);
                                    timer.Tick += delegate(object s, object args)
                                    {
                                        image.PlayToSource.PlayNext();
                                    };
                                    timer.Start();
                                }
    
                                if (currentImage == num)
                                {
                                    MessageBlock.Text = "Slideshow rendering";
                                }
                           }); 
                    break;
                }
            };
    
        return image;
    }
    
    var states = Windows.Media.PlayTo.PlayToConnectionState, // alias for PlayToConnectionState
        imageList,               // contains the list of images to show
        streaming = false,       // true when streaming using Play To; otherwise false
        cancel = 0,              // used to cancel a timeout
        timeLapse = 5,           // time between images (5 seconds)
        imageSize = "600px",     // size of current displayed image
        thumbnailSize = "200px", // size of "thumbnail" of next image
        currentImage = 0;        // index of the current image from imageList
    
    // Get the list of images from the Pictures folder and start the slide show.
    
    function startSlideShow() {
        Windows.Storage.KnownFolders.picturesLibrary.getFilesAsync().then(
            function (resultsLibrary) {
                imageList = resultsLibrary;
                if (imageList.length > 0) {
                    var image = queueImage(0, true);
                } else {
                    id("messageDiv").innerHTML = "There are no images in the Pictures library.";
                }
            });
    }
    
    
    // playNextImage
    // Called when a new image is displayed due to a timeout.
    // Removes the current image object and queues a new next image.
    // Sets the next image index as the new current image, and increases the size 
    // of the new current image. Then sets the timeout to display the next image.
    
    function playNextImage(num) {
        id("slideshowDiv").removeChild(id("image" + num));
        queueImage(num + 2, false);
    
        currentImage = num + 1;
        id("image" + currentImage).style.width = imageSize;
    
        cancel = setTimeout(function () {
            playNextImage(num + 1);
        }, timeLapse * 1000);
    }
    
    
    // queueImage
    // Called to create an image object for the displayed images.
    
    function queueImage(num, isFirstImage) {
    
        // Create the image element for the specified image index and add to the
        // slide show div.
    
        var image = document.createElement("img");
        image.style.width = (isFirstImage ? imageSize : thumbnailSize);
        image.id = "image" + num;
        image.src = URL.createObjectURL(imageList[num % imageList.length], { oneTimeOnly: true });
        id("slideshowDiv").appendChild(image);
    
        // If this is the first image of the slide show, queue the next image. Do
        // not queue if streaming as images are already queued before
        // streaming using Play To.
    
        if (isFirstImage && !streaming) {
    
            queueImage(num + 1, false);
    
            cancel = setTimeout(function () {
                playNextImage(num);
            }, timeLapse * 1000);            
        }
    
        // Use the transferred event of the Play To connection for the current image object
        // to "move" to the next image in the slide show. The transferred event occurs
        // when the PlayToSource.playNext() method is called, or when the Play To
        // Receiver selects the next image.
    
        image.msPlayToSource.connection.addEventListener("transferred", function () {
    
            currentImage = num + 1;
            id("image" + currentImage).style.width = imageSize;
    
        }, false);
    
    
        // Use the statechanged event to determine which action to take or to respond
        // if the Play To Receiver is disconnected.
        image.msPlayToSource.connection.addEventListener("statechanged", function (e) {
    
            switch (e.currentState) {
                case states.disconnected:
    
                    // If the state is disconnected and the current image index equals the 
                    // num value passed to queueImage, then the image element is not connected 
                    // to the Play To Receiver any more. Restart the slide show.
                    // Otherwise, the current image has been discarded and the slide show
                    // has moved to the next image. Clear the current image object and
                    // remove it from the slide show div.
    
                    if (currentImage == num) {
                        id("messageDiv").innerHTML = "Slideshow disconnected";
    
                        // Cancel any existing timeout
                        if (cancel) {
                            clearTimeout(cancel);
                        }
    
                        // Clear all image objects from the slide show div
                        while (id("slideshowDiv").firstChild) {
                            id("slideshowDiv").removeChild(id("slideshowDiv").firstChild);
                        }
    
                        // Reset the slide show objects and values to their beginning state
                        streaming = false;
                        id("disconnectButton").style.display = "none";
                        id("instructionsDiv").style.display = "block";
                        disconnectButton.removeEventListener("click", disconnectButtonClick, false);
    
                        // Restart the slide show from the current image index
                        queueImage(currentImage, true);
                    } else {
                        image.msPlayToSource.next = null;
                        image.removeAttribute("src");
    
                        if (streaming) {
                            id("slideshowDiv").removeChild(image);
                        }
                    }
    
                    break;
                    
                case states.connected:
    
                    // If the state is connected and the previous state is disconnected, 
                    // then the image element is newly connected. Queue up the next image so 
                    // that it is loaded while the current image is being displayed.
                    // If the previous state is rendering, then the user has paused the slideshow 
                    // on the Play To Receiver. Clear the current timeout until the user restarts
                    // the slide show.
    
                    if (e.previousState === states.disconnected) {
                        var imageNext = queueImage(num + 1, false);
                        image.msPlayToSource.next = imageNext.msPlayToSource;
                    } else if (e.previousState === states.rendering) {
                        if (cancel) {
                            clearTimeout(cancel);
                            cancel = 0;
                        }
                    }
    
                    if (currentImage == num) {
                        id("messageDiv").innerHTML = "Slideshow connected";
                    }
    
                    break;
    
                case states.rendering:
    
                    // If the state is rendering and the previous state is
                    // connected, then the Play To Receiver has restarted
                    // the slide show.
    
                    if (e.previousState === states.connected) {
    
                        // Clear any existing timeout.
                        if (cancel) {
                            clearTimeout(cancel);
                        }
    
                        // Restart the slide show.
                        cancel = setTimeout(function () {
                            image.msPlayToSource.playNext();
                        }, timeLapse * 1000);
                    }
    
                    if (currentImage == num) {
                        id("messageDiv").innerHTML = "Slideshow rendering";
                    }
    
                    break;
            }
    
        }, false);
    
        return image;
    }
    
    Private imageList As IReadOnlyList(Of Windows.Storage.StorageFile)    ' contains the list of images to show
    Private streaming As Boolean = False       ' true when streaming using Play To otherwise false
    Private timeLapse As Integer = 5           ' time between images (5 seconds)
    Private imageSize As Integer = 600         ' size of current displayed image
    Private thumbnailSize As Integer = 200     ' size of "thumbnail" of next image
    Private currentImage As Integer = 0        ' index of the current image from imageList
    
    ' Get the list of images from the Pictures folder and start the slide show.
    Private Async Sub StartSlideShow()
        Dim resultsLibrary =
            Await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync()
        imageList = resultsLibrary
        If (imageList.Count > 0) Then
            Dim image = QueueImage(0, True)
        Else
            MessageBlock.Text = "There are no images in the Pictures library."
        End If
    End Sub
    
    ' PlayNextImage
    ' Called when a new image is displayed due to a timeout.
    ' Removes the current image object and queues a new next image.
    ' Sets the next image index as the new current image, and increases the size 
    ' of the new current image. Then sets the timeout to display the next image.
    
    Private Async Sub PlayNextImage(num As Integer)
        ' Stop the timer to avoid repeating.
        If timer IsNot Nothing Then timer.Stop()
    
        Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            Async Sub()
                SlideShowPanel.Children.Remove(CType(SlideShowPanel.FindName("image" & num), UIElement))
                Dim i = Await QueueImage(num + 2, False)
    
                currentImage = num + 1
                CType(SlideShowPanel.FindName("image" & currentImage), Image).Width = imageSize
            End Sub)
    
        timer = New Windows.UI.Xaml.DispatcherTimer()
        timer.Interval = New TimeSpan(0, 0, timeLapse)
        AddHandler timer.Tick, Sub(sender As Object, e As Object)
                                   PlayNextImage(num + 1)
                               End Sub
        timer.Start()
    End Sub
    
    ' QueueImage
    ' Called to create an image object for the displayed images.
    
    Private Async Function QueueImage(num As Integer, isFirstImage As Boolean) As Task(Of Image)
        ' Create the image element for the specified image index and add to the
        ' slide show div.
    
        Dim image = New Image()
        image.Width = If(isFirstImage, imageSize, thumbnailSize)
        image.Name = "image" & num
        image.VerticalAlignment = VerticalAlignment.Bottom
        Dim fileContents = Await imageList(num Mod imageList.Count).OpenReadAsync()
        Dim imageBitmap = New BitmapImage()
        imageBitmap.SetSource(fileContents)
        image.Source = imageBitmap
    
        Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            Sub()
                SlideShowPanel.Children.Add(image)
            End Sub)
    
        ' If this is the first image of the slide show, queue the next image. Do
        ' not queue if streaming as images are already queued before
        ' streaming using Play To.
    
        If isFirstImage AndAlso Not streaming Then
    
            Dim i = Await QueueImage(num + 1, False)
    
            timer = New Windows.UI.Xaml.DispatcherTimer()
            timer.Interval = New TimeSpan(0, 0, timeLapse)
            AddHandler timer.Tick, Sub(sender As Object, e As Object)
                                       PlayNextImage(num)
                                   End Sub
            timer.Start()
        End If
    
    ' Use the transferred event of the Play To connection for the current image object
    ' to "move" to the next image in the slide show. The transferred event occurs
    ' when the PlayToSource.playNext() method is called, or when the Play To
    ' Receiver selects the next image.
    
        AddHandler image.PlayToSource.Connection.Transferred,
            Async Sub(sender As Windows.Media.PlayTo.PlayToConnection,
                      e As Windows.Media.PlayTo.PlayToConnectionTransferredEventArgs)
    
                currentImage = num + 1
    
                Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                    Sub()
                        CType(SlideShowPanel.FindName("image" & currentImage), Image).Width = imageSize
                    End Sub)
            End Sub
    
    
        ' Use the statechanged event to determine which action to take or to respond
        ' if the Play To Receiver is disconnected.
        AddHandler image.PlayToSource.Connection.StateChanged,
            Async Sub(sender As Windows.Media.PlayTo.PlayToConnection,
                      e As Windows.Media.PlayTo.PlayToConnectionStateChangedEventArgs)
    
                Select Case e.CurrentState
                    Case Windows.Media.PlayTo.PlayToConnectionState.Disconnected
    
                        ' If the state is disconnected and the current image index equals the 
                        ' num value passed to queueImage, then the image element is not connected 
                        ' to the Play To Receiver any more. Restart the slide show.
                        ' Otherwise, the current image has been discarded and the slide show
                        ' has moved to the next image. Clear the current image object and
                        ' remove it from the slide show div.
    
                        If currentImage = num Then
                            Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                Async Sub()
                                    MessageBlock.Text = "Slideshow disconnected"
    
                                    ' Cancel any existing timeout
                                    If timer IsNot Nothing Then timer.Stop()
    
                                    ' Clear all image objects from the slide show div
                                    SlideShowPanel.Children.Clear()
    
                                    ' Reset the slide show objects and values to their beginning state
                                    streaming = False
                                    DisconnectButton.Visibility = Visibility.Collapsed
                                    InstructionsBlock.Visibility = Visibility.Visible
                                    AddHandler DisconnectButton.Click, AddressOf DisconnectButtonClick
    
                                    ' Restart the slide show from the current image index
                                    Dim i = Await QueueImage(currentImage, True)
                                End Sub)
                        Else 
                               Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                    Sub()
                                        image.PlayToSource.Next = Nothing
    
                                        If streaming Then
                                            SlideShowPanel.Children.Remove(image)
                                        End If
                                    End Sub)
                        End If
    
                    Case Windows.Media.PlayTo.PlayToConnectionState.Connected
    
                    ' If the state is connected and the previous state is disconnected, 
                    ' then the image element is newly connected. Queue up the next image so 
                    ' that it is loaded while the current image is being displayed.
                    ' If the previous state is rendering, then the user has paused the slideshow 
                    ' on the Play To Receiver. Clear the current timeout until the user restarts
                    ' the slide show.
                    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                        Async Sub()
                                If e.PreviousState = Windows.Media.PlayTo.PlayToConnectionState.Disconnected Then
                                    Dim imageNext = Await QueueImage(num + 1, False)
                                    image.PlayToSource.Next = imageNext.PlayToSource
                                ElseIf e.PreviousState = Windows.Media.PlayTo.PlayToConnectionState.Rendering Then
                                    If timer IsNot Nothing Then timer.Stop()
                                End If
    
                                If currentImage = num Then
                                    MessageBlock.Text = "Slideshow connected"
    
                                End If
                            End Sub)
    
                    Case Windows.Media.PlayTo.PlayToConnectionState.Rendering
    
                    ' If the state is rendering and the previous state is
                    ' connected, then the Play To Receiver has restarted
                    ' the slide show.
                    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                       Sub()
                               If e.PreviousState = Windows.Media.PlayTo.PlayToConnectionState.Connected Then
    
                                   ' Clear any existing timeout.
                                   If timer IsNot Nothing Then timer.Stop()
    
                                   ' Restart the slide show.
                                   timer = New Windows.UI.Xaml.DispatcherTimer()
                                   timer.Interval = New TimeSpan(0, 0, timeLapse)
                                   AddHandler timer.Tick, Sub(s As Object, args As Object)
                                                              image.PlayToSource.PlayNext()
                                                          End Sub
                                   timer.Start()
                               End If
    
                               If currentImage = num Then
                                   MessageBlock.Text = "Slideshow rendering"
                               End If
                           End Sub)
                End Select
                End Function
    
        Return image
    End Function
    

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.DeprecatedAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.MuseAttribute
Windows.Foundation.Metadata.ThreadingAttribute

Details

Assembly

Windows.Media.PlayTo.dll