Menu
23
MAUI

🗓️ Day 4 – Carousel Swipe & Auto-Play

Post image

 

## **Day 4 – Carousel Media Player in .NET MAUI**

In this lesson, we upgraded our simple media player to support multiple videos using a **CarouselView**.
Instead of one video, users can now swipe up or down to switch between movies — just like TikTok or Reels.

---

### **Overview**

For now, the movie list is **hardcoded** inside the `MainPage.xaml.cs`.
In the next lesson, we’ll load the movies **dynamically from Firebase**.
These current videos are from **Google APIs** for testing.

---

### **Steps**

1. **Add CommunityToolkit for MediaElement**
   Install this NuGet package:

   ```
   CommunityToolkit.Maui.MediaElement
   ```

   Then register it in `MauiProgram.cs`:

   ```csharp
   builder.UseMauiCommunityToolkitMediaElement();
   ```

2. **Create a CarouselView in XAML**

   ```xml
   <CarouselView x:Name="MoviesCarousel"
                 ItemsSource="{Binding Movies}"
                 Loop="False"
                 PeekAreaInsets="0"
                 IndicatorView="{x:Null}">
       <CarouselView.ItemsLayout>
           <LinearItemsLayout Orientation="Vertical" />
       </CarouselView.ItemsLayout>

       <CarouselView.ItemTemplate>
           <DataTemplate>
               <Grid BackgroundColor="Black">
                   <toolkit:MediaElement x:Name="MediaPlayer"
                                         Source="{Binding MovieLink}"
                                         ShouldAutoPlay="False"
                                         ShouldShowPlaybackControls="False"
                                         Aspect="AspectFill" />
                   <StackLayout VerticalOptions="End" Padding="20" BackgroundColor="#80000000">
                       <Label Text="{Binding MovieTitle}" TextColor="White" FontSize="20" FontAttributes="Bold"/>
                       <Label Text="{Binding MoviesName}" TextColor="LightGray" FontSize="16"/>
                   </StackLayout>
               </Grid>
           </DataTemplate>
       </CarouselView.ItemTemplate>
   </CarouselView>
   ```

3. **Add Movie Data (Code-Behind)**
   In your `MainPage.xaml.cs`, create a simple `Movies` list with sample links (from Google APIs).
   Each movie has:

   * Title
   * Description
   * Link
   * Release Date

   These are added to an `ObservableCollection<Movies>` and displayed automatically.

4. **Add Auto-Play Logic**
   When the user swipes, detect the new position and:

   * Pause the previous video
   * Play the current one
   * Optionally preload the next for smoother playback

   (All this logic is already in the provided code file — see GitHub link below.)

---

### **Testing**

Run the app — swipe up or down to move between videos.
Each video plays automatically as it becomes visible.

---

### **Next Lesson →**

In **Day 5**, we’ll connect the app to **Firebase Firestore**, so videos will load dynamically from the database instead of being hardcoded.