新的 Xamarin Forms 4.6 MediaElement 不适用于 Android

New Xamarin Forms 4.6 MediaElement not working for Android

我在一个非常简单的 Xamarin Forms Shell 项目中试用了新的 Xamarin Forms 4.6.0.726 MediaElement 控件。 我在 ContentPage 中添加了 MediaElement 控件并设置了它的属性(AutoPlay 为 true,IsLooping 为 true,Source 为 mp4 文件,ShowPlaybackControls 为 true)。 我还在 App.xaml.cs.

中为 MediaElement 添加了 Experimental-Flag

当我 运行 应用程序时,视频在 iOS 上播放,声音、图像和播放器控件可见,但在 Android 上不起作用。 在 Android 上,播放器控件未显示,没有任何反应。

还有其他人遇到过这个问题吗?

您可以尝试检查这些,确保您在平台项目中存储了媒体文件。

在 Android,媒体文件必须存储在名为 rawResources 的子文件夹中。 raw 文件夹不能包含子文件夹。媒体文件必须具有 AndroidResourceBuild Action

然后在你的 page.xaml 中(不要使用布局来包装 MediaElement):

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MediaElementDemos.PlayAppPackageVideoResourcePage"
         Title="Play app package video resource">
    <MediaElement Source="ms-appx:///XamarinForms101UsingEmbeddedImages.mp4"
              ShowsPlaybackControls="True" IsLooping="True" AutoPlay="True" />
</ContentPage>

在你的App.xaml.cs

中添加Device.SetFlags(new string[] { "MediaElement_Experimental" });
public App()
    {
        Device.SetFlags(new string[] { "MediaElement_Experimental" });
        InitializeComponent();
        MainPage = new NavigationPage(new PlayPage());
    }

更新:

如果您想从URL播放mp4。

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     x:Class="MediaElementDemos.PlayAppPackageVideoResourcePage"
     Title="Play app package video resource">
    <MediaElement Source="https://sec.ch9.ms/ch9/5d93/a1eab4bf-3288-4faf-81c4-294402a85d93/XamarinShow_mid.mp4"
          ShowsPlaybackControls="True" IsLooping="True" AutoPlay="True" />
</ContentPage>

我必须根据这篇文章在上述答案之上添加一些内容才能使其正常工作:https://github.com/xamarin/Xamarin.Forms/issues/9785

Device.StartTimer(TimeSpan.FromSeconds(1), () =>
            {
                videoPlayer.Play();

                videoPlayer.ScaleTo(0.99f);
                videoPlayer.ScaleTo(1.00f);

                return false;
            });

确保在添加之前添加以上答案。