Media Player support for Web Assembly in UNO

Viewed 494

I was developing an APP on UNO for playing Videos. It works fine on other platforms except for WASM. I checked the code and realized that MediaPlayerElement is not implemented for Web Assembly.

Is there any workaround for that available currently or is it a work in progress and will be available soon, or Am I missing something here?

1 Answers

For playing media on an Uno Platform WebAssembly app you can look at the HtmlMediaPlayer implementation in the Ch9 app. The full code is below.

There's a couple of points to note:

  • The HtmlElement attribute tells Uno to create a <video/> tag as the underlying DOM element for this control
  • The OnSourceChanged() callback passes the Source to the native <video/> by using the ExecuteJavascript() extension method from Uno.
    [HtmlElement("video")]
    public sealed partial class HtmlMediaPlayer : Border
    {
        public HtmlMediaPlayer()
        {
            Background = new SolidColorBrush(Colors.Transparent);
        }

        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
            "Source", typeof(string), typeof(HtmlMediaPlayer), new PropertyMetadata(default(string), OnSourceChanged));

        public string Source
        {
            get => (string)GetValue(SourceProperty);
            set => SetValue(SourceProperty, value);
        }

        private static async void OnSourceChanged(DependencyObject dependencyobject, DependencyPropertyChangedEventArgs args)
        {
            if (dependencyobject is HtmlMediaPlayer player)
            {
                var encodedSource = WebAssemblyRuntime.EscapeJs("" + args.NewValue);
                var js = $"element.controls = true; element.src=\"{encodedSource}\";";
                player.ExecuteJavascript(js);
            }
        }
    }

You can see in Ch9 how this is used as a drop-in replacement for MediaPlayerElement:

            <not_wasm:MediaPlayerElement x:Name="MediaPlayer"
                                         Source="{Binding VideoSource}"
                                         IsFullWindow="{Binding Parent.IsVideoFullWindow, Mode=TwoWay}"
                                         Height="180" />
            <wasm:Border>
                <localwasm:HtmlMediaPlayer x:Name="MediaPlayer"
                                           Height="180"
                                           Source="{Binding VideoUri}" />
            </wasm:Border>

Proper MediaPlayerElement support will likely be added to Uno Platform in the future, you can help prioritize it by upvoting the issue.

Related