By Peter Foot
Peter is a Xamarin-certified Mobile Developer and Microsoft Windows Development MVP. He has been building mobile and embedded software for over 15 years. He focuses on Xamarin and Windows platforms and writes about them @peterfoot and on his website.
Xamarin Forms has a rich set of controls which work natively across platforms. However, a big gap in functionality is the ability to play audio or video content.
You can create custom controls for Xamarin, and you have full access to the APIs for each platform-specific renderer to create complex controls of your own. I’ve needed to display a video for a couple of projects and it felt to me like a fairly standard control we take for granted when doing “native” development.
The good news is that you don’t have to do this yourself because I’ve built a custom control, and it’s ready to roll for Android, iOS and Windows. If you’ve used the Windows MediaElement then you already know how to use it, too:
Simply add the InTheHand.Forms NuGet package, add a namespace to your XAML and add the MediaElement control. You can do the basics straight from XAML, but you can add a name to the control and interact with it from the code too. You can find full documentation for the control online.
The standard player controls can be toggled using the AreTransportControlsEnabled property. The displayed controls will match the native appearance of the target platform. For example, the code sample above uses a link to a Channel 9 video on Xamarin Auth by @HoussemDellai and you can see below how it is rendered on an Android app and a UWP desktop app:
Your source files could come from several locations. I’ve tried to make it as easy as possible to refer to these using a common Uri scheme so I’ve followed the UWP model:
Specifies a file within your application package. For Windows this means a Build Action of Content, for iOS BundleResource and for Android as AndroidResource within the Resources/raw folder.
Specifies a path within your apps local storage. If your app downloads files from a server or generates them locally you might use this location. This path in the file system can be found using Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) on Android and iOS and Windows.Storage.ApplicationData.Current.LocalData on Windows.
A full path on the local file system – device specific and requires your app to have the appropriate permissions to access the folder.
A file hosted online.
Call to Action
I hope you find this useful in adding media to your Xamarin Forms projects!