Implementing Chromecast with Uno Platform Applications

If you’re building a video or audio application with Uno Platform, you can easily include Chromecast Support. In this article, using a simple XAML design with TextBox, Button, TextBlock and Listview we walk through the steps to cast a simple app to communicate with. 

Before we get started, there are a few initial steps to be taken.

Prerequisits

For this tutorial, we are using Uno Platform on a Mac, but you can follow the instructions on Windows as well. If you are new to Uno Platform please setup Uno Platform on your machine first:

Windowshttps://platform.uno/docs/articles/get-started-vs.html
VS Codehttps://platform.uno/docs/articles/get-started-vscode.html
Machttps://platform.uno/docs/articles/get-started-vsmac.html

To create Uno Platform projects using the command line, you also need to install the templates by following these instructions here: dotnet new templates for Uno Platform.

Chromecast

Chromecast allows streaming videos in the background with remote devices (TV, Google mini). Before a Cast session can begin, both the sender device (for example, a mobile phone or tablet) and the receiver device (for example, a Chromecast plugged into a TV) must be connected to the same Wi-Fi network. For more info, please refer to the below URL.

Limitation: Chromecast does not support local media files.

Create New Uno Platform App Project

First off, we need to create a new project from the command line.

Follow the below command.

				
					cd src
dotnet new unoapp -o UnoApp
				
			

Setup UI

MainPage.xaml

We are now going to create a simple XAML design with TextBoxButton, TextBlock and Listview for the Chromecast example.

  1. TextBox – Getting Media file input as a url

  2. Button – Start Streaming the media file

  3. TextBlock – To show the message if there is no receiver connected.

  4. ListView – To list the connected chromecast devices in our network.

Applied some MVVM Binding.

				
					<Page
    x:Class="UnoApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UnoApp1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid Margin="15,100">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBox Grid.Row="0" Grid.ColumnSpan="2" Header="Enter Media URL" Text="{Binding CastUrl, Mode=TwoWay}" PlaceholderText="Enter Cast URL" />
        <ListView Grid.Row="1" Grid.ColumnSpan="2" MinimumHeightRequest="100" SelectionMode="Single" ItemsSource="{Binding CastDevices}" SelectedItem="{Binding SelectedCastDevice}">
            <ListView.ItemTemplate>
                <DataTemplate>
                     <TextBlock Text="{Binding FriendlyName}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <TextBlock Margin="20"  x:Name="lblNoReciverMessage" Grid.Row="2"/>
        <Button HorizontalAlignment="Center"  Grid.Row="3" Grid.Column="0" Content="Start Cast" Click="StartCast_Click" />
        <Button HorizontalAlignment="Center"  Grid.Row="3" Grid.Column="1" Content="Refresh" Click="Refresh_Click" />
    </Grid>
</Page>

				
			

Install GoogleCast Nuget

We use this package to check what Chromecast devices are connected to our network and to load and play the media to the selected device.


Go to Solution Explorer and select your solution. Right-click and select “Manage NuGet Packages for Solution”. Search “GoogleCast” and add Package. Remember to install it for all platforms.

You can check here for additional details about GoogleCast.

Get Receiver

Let’s first get all connected Chromecasts devices in your network. Use the following code snippets to get receiver devices.

The GetReceivers method needs to be called when the page loads – in its constructor or in the `Loaded` event handler. After getting all received devices we need to add them to the ObservableCollection<IReceiver> which we have bound to the ListView in XAML UI. 

				
					private async Task GetReceivers()
        {
            // Use the DeviceLocator to find all connected Chromecasts on our network
            IEnumerable<IReceiver> receivers = await new DeviceLocator().FindReceiversAsync();

            CastDevices = new ObservableCollection<IReceiver>();
            if (receivers != null && receivers.ToList().Count > 0)
            {
                foreach (var r in receivers)
                    CastDevices.Add(r);
            }
            else
            {
                lblNoReciverMessage.Text = "No receiver is found";
            }

            DataContext = this;

        }

				
			

Refresh

Click the refresh button to get the connected receivers.

				
					void Refresh_Click(System.Object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
     GetReceivers();
}

				
			

Start Casting

Play your media file in your connected Chromecast device.

Whenever we click the StartCast Button we need to call the StartCasting Method in Code behind. It will get the SelectedCastDeviceand stream the media file into the Selected Chromecast Device.

Use a media file as a URL to play on a Chromecast device.

				
					public string CastUrl { get; set; } = "https://icecast-qmusicnl-cdp.triple-it.nl/Qmusic_nl_live_32.aac";
				
			
				
					//Start Stream video
        async void StartCasting()
        {
            var sender = new Sender();
            // Connect to the Chromecast
            await sender.ConnectAsync(SelectedCastDevice);
            // Launch the default media receiver application
            var mediaChannel = sender.GetChannel<IMediaChannel>();
            await sender.LaunchAsync(mediaChannel);
            // Load and play video
            var mediaStatus = await mediaChannel.LoadAsync(
                new MediaInformation() { ContentId = CastUrl });
        }

				
			

Debug Your App

Run your Uno Platform app on your preferred platform, I’m going to run in an iOS simulator.


Once your app is running, you can see the Media URL. You can change it to whatever you prefer and then select any Connected Chromecast device to start casting.

Next Steps

Full working source code is available in the following GitHub repository

If you are new to Uno Platform, the best way to get started is to follow our official getting started guide. For better discoverability and ease of adopting Uno Platform, we have brushed up and published various working examples for Uno Platform, ranging from small single-feature samples to larger showcase applications.

Share this post:
Join us for a live-webinar on everything Uno Platform 5.0 Dec 12th, at noon EST.
Save to calendar