PlayToSource Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Представляет элемент мультимедиа для подключения к целевому объекту воспроизведения.
public ref class PlayToSource sealed
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.Deprecated("PlayToSource may be altered or unavailable for releases after Windows 10. Instead, use CastingSource.", Windows.Foundation.Metadata.DeprecationType.Deprecate, 65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class PlayToSource final
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
/// [Windows.Foundation.Metadata.Deprecated("PlayToSource may be altered or unavailable for releases after Windows 10. Instead, use CastingSource.", Windows.Foundation.Metadata.DeprecationType.Deprecate, 65536, "Windows.Foundation.UniversalApiContract")]
class PlayToSource final
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.Deprecated("PlayToSource may be altered or unavailable for releases after Windows 10. Instead, use CastingSource.", Windows.Foundation.Metadata.DeprecationType.Deprecate, 65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class PlayToSource
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
[Windows.Foundation.Metadata.Deprecated("PlayToSource may be altered or unavailable for releases after Windows 10. Instead, use CastingSource.", Windows.Foundation.Metadata.DeprecationType.Deprecate, 65536, "Windows.Foundation.UniversalApiContract")]
public sealed class PlayToSource
Public NotInheritable Class PlayToSource
- Наследование
- Атрибуты
Требования к Windows
Семейство устройств |
Windows 10 (появилось в 10.0.10240.0)
|
API contract |
Windows.Foundation.UniversalApiContract (появилось в v1.0)
|
Примеры
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;
}
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. initialImage 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. initialImage 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
Комментарии
Пример использования класса PlayToSource см. в разделе Приведение мультимедиа.
Свойства
Connection |
Получает подключение к целевому объекту "Воспроизвести". |
Next |
Возвращает или задает следующий исходный элемент Play To. |
PreferredSourceUri |
Указывает предпочтительный универсальный код ресурса (URI) для потока мультимедиа, например облачный сервер мультимедиа, используемый для воспроизведения по ссылке. |
Методы
PlayNext() |
Подключает следующий исходный элемент Play To к целевому объекту Play To. |