How to set Grid.Background to MediaPlayer in UWP?

298 Views Asked by At

How to add video to Grid.Background in UWP app?

In previous version, I used

<Grid.Background>
    <ImageBrush ImageSource="ms-appx:///Assets/carosel3.jpg" Stretch="UniformToFill"/>
</Grid.Background>
1

There are 1 best solutions below

0
Martin Zikmund On

There are two ways how to accomplish this in UWP.

Composition APIs

The Composition APIs offer CompositionSurfaceBrush with which you can paint an area with pixels rendered using a video through MediaPlayer. Example from the documentation:

Compositor _compositor = ElementCompositionPreview.GetElementVisual(MyGrid).Compositor;
SpriteVisual _videoVisual;
CompositionSurfaceBrush _videoBrush;

// MediaPlayer set up with a create from URI

_mediaPlayer = new MediaPlayer();

// Get a source from a URI. This could also be from a file via a picker or a stream
var source = MediaSource.CreateFromUri(new Uri("https://www.example.com/video.mp4"));
var item = new MediaPlaybackItem(source);
_mediaPlayer.Source = item;
_mediaPlayer.IsLoopingEnabled = true;

// Get the surface from MediaPlayer and put it on a brush
_videoSurface = _mediaPlayer.GetSurface(_compositor);
_videoBrush = _compositor.CreateSurfaceBrush(_videoSurface.CompositionSurface);

_videoVisual = _compositor.CreateSpriteVisual();
_videoVisual.Brush = _videoBrush;

Check the docs for more information on look for one of many tutorials on using Composition APIs on the internet (like here).

Separate `MediaPlayer element

A simpler solution would be to just place a MediaPlayerElement under the Grid itself. When the Grid has Transparent background, the video will appear below the Grid.

<Grid>
    <MediaPlayerElement x:Name="mediaPlayer"
                      AreTransportControlsEnabled="False"
                      Source="ms-appx:///SomeVideo.mp4" />
    <Grid>
       ... your content
    </Grid>
</Grid>