Xamarin.Forms学习之路——MediaManager Nuget学习

Xamarin.Forms学习之路——MediaManager Nuget学习

  • Demo效果图
  • 学习目标
  • Demo结构
  • Demo准备
  • 步骤
    • 修改Xamarin.Forms.Andriod属性(重要)
    • 修改Xamarin.Forms.Android.MainActivity.cs文件
    • 修改MainPage.xaml
    • 修改MainPage.xaml.cs
    • 添加嵌入式资源
  • 欢迎交流

参考https://github.com/Baseflow/XamarinMediaManager/blob/develop/MediaManager.Forms/

Demo效果图

Xamarin.Forms学习之路——MediaManager Nuget学习_第1张图片

学习目标

  • 音视频播放器MediaManager Nuget 包的简单使用
  • 音频的控制

Demo结构

如下图所示,视频、音频资源可自行寻找
Xamarin.Forms学习之路——MediaManager Nuget学习_第2张图片

Demo准备

  1. 按照Demo结构所示新建文件夹;
  2. 添加自己准备好的多媒体文件;
  3. 安装MediaManager.Forms.View和MediaManager Nuget包,不要管Demo结构中的Xam……包,那个是搞忘移除了……这次重点学习MediaManager。

步骤

修改Xamarin.Forms.Andriod属性(重要)

根据原项目文档
Xamarin.Forms学习之路——MediaManager Nuget学习_第3张图片
将DexTool调整至D8
Xamarin.Forms学习之路——MediaManager Nuget学习_第4张图片

修改Xamarin.Forms.Android.MainActivity.cs文件

初始化CrossMediaManager

using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using MediaManager.Forms.Platforms.Android;
using MediaManager;

namespace MusicPlayerDemo.Droid
{
    [Activity(Label = "MusicPlayerDemo", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            //初始化CrossMediaManager
            CrossMediaManager.Current.Init();

            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

修改MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:video="clr-namespace:MediaManager.Forms;assembly=MediaManager.Forms"
             mc:Ignorable="d"
             x:Class="MusicPlayerDemo.MainPage">
    
    <ContentPage.Content>
        <ScrollView HeightRequest="1000">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="4*"></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>

                <video:VideoView
                    x:Name="video"
                    VerticalOptions="Center"
                    HorizontalOptions="Center"
                    ShowControls="True" 
                    Grid.Row="0"
                    VideoPlaceholder="_1.jpg">
                </video:VideoView>

                <Button
                    Text="加载资源"
                    Clicked="Button_Clicked"
                    Grid.Row="1"></Button>
                <Button
                    Text="查看Buffer"
                    Grid.Row="2"
                    Clicked="Button_Clicked_1"></Button>
                <Button
                    Text="歌曲时长"
                    Grid.Row="3"
                    Clicked="Button_Clicked_2"></Button>
                <Button
                    Text="歌曲State"
                    Grid.Row="4"
                    Clicked="Button_Clicked_3"></Button>
                <Button
                    Text="更改壁纸"
                    Grid.Row="5"
                    Clicked="Button_Clicked_4"></Button>
                <Button
                    Text="暂停"
                    Grid.Row="6"
                    Clicked="Button_Clicked_5"></Button>
                <Button
                    Text="播放"
                    Grid.Row="7"
                    Clicked="Button_Clicked_6"></Button>
                <Button
                    Text="前跳一帧"
                    Grid.Row="8"
                    Clicked="Button_Clicked_7"></Button>
                <Button
                    Text="后跳一帧"
                    Grid.Row="9"
                    Clicked="Button_Clicked_8"></Button>
                <Button
                    Text="下一首"
                    Grid.Row="10"
                    Clicked="Button_Clicked_9"></Button>
                <Button
                    Text="上一首"
                    Grid.Row="11"
                    Clicked="Button_Clicked_10"></Button>
            </Grid>
        </ScrollView>
    </ContentPage.Content>
    

</ContentPage>

修改MainPage.xaml.cs

using MediaManager;
using MediaManager.Forms;
using MediaManager.Library;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace MusicPlayerDemo
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        private int click;
        public MainPage()
        {
            //会遇到问题编译问题defining a default interface method requires --min-sdk-version >= 24 (currently 13) for interface methods: com.google.android.exoplayer2。
            //参考http://www.firelamb.com/Article/Detail/525
            //修改Xamarin.andriod项目配置即可
            InitializeComponent();
        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            click++;
            Debug.WriteLine(click);

            ///测试一:
            ///不建立sharedresource文件夹
            ///测试成功
            /*var assembly = GetType().GetTypeInfo().Assembly;
                //下面这种用法失败了,原因不是很清楚
                //CrossMediaManager.Current.PlayFromResource("assets:///demo.mp3")
            CrossMediaManager.Current.PlayFromAssembly("demo.mp3",assembly);*/

            ///测试二
            ///测试成功,不过外链mp3链接不稳定
            //CrossMediaManager.Current.Play("https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/01_-_Intro_-_The_Way_Of_Waking_Up_feat_Alan_Watts.mp3");

            ///测试三
            ///建立Sharedresource文件夹
            ///测试成功

            //获取MainPage所在的程序集——MusicPlayerDemo
            Assembly assembly = GetType().GetTypeInfo().Assembly;
            //加载多首歌
            var demo = await CrossMediaManager.Current.PlayFromAssembly("demo.mp3", assembly);
            var demo2 = await CrossMediaManager.Current.PlayFromAssembly("demo2.mp3", assembly);
            List<IMediaItem> mediaManagers = new List<IMediaItem>();
            mediaManagers.Add(demo);
            mediaManagers.Add(demo2);
            await CrossMediaManager.Current.Play(mediaManagers);
            CrossMediaManager.Current.BufferedChanged += Current_BufferedChanged;
            //无效,不明所以
            video.VideoPlaceholder = "_1.jpg";
            
            
            //Debug.WriteLine("w:" + video.Source);
        }

        private void Current_BufferedChanged(object sender, MediaManager.Playback.BufferedChangedEventArgs e)
        {
            //throw new NotImplementedException();
           
            DisplayAlert(" ", e.ToString(), "cancel");
        }

        private void Button_Clicked_1(object sender, EventArgs e)
        {
            DisplayAlert(" ", CrossMediaManager.Current.Buffered.ToString(), "cancel");
            
        }

        private void Button_Clicked_2(object sender, EventArgs e)
        {
            DisplayAlert(" ", CrossMediaManager.Current.Duration.ToString(), "cancel");
        }

        private void Button_Clicked_3(object sender, EventArgs e)
        {
            DisplayAlert(" ", CrossMediaManager.Current.State.ToString(), "cancel");

        }

        private void Button_Clicked_4(object sender, EventArgs e)
        {
            //好像并不支持自定义placeholder,不过这并不碍事
            //只能更换本地图片
            //if (newValue is Xamarin.Forms.ImageSource imageSource)
            //  MediaManager.MediaPlayer.VideoPlaceholder = await imageSource.ToNative().ConfigureAwait(false);
            //https://github.com/Baseflow/XamarinMediaManager/blob/develop/MediaManager.Forms/VideoView.cs
            var random = new Random().Next(0, 3);
            if(random == 0)
            {
                //video.VideoPlaceholder = _1.Source;
                
            }
            if (random == 1)
            {

               // video.VideoPlaceholder = image.ToImageSource();
                //DisplayAlert("Image", image.ToImageSource().ToString(), "cancel");
            }
            if (random == 2)
            {
                //video.VideoPlaceholder = image.ToImageSource();
                //DisplayAlert("Image", image.ToImageSource().ToString(), "cancel");
            }
             
            
            //FileImageSource
            //DisplayAlert("VideoPlaceHolder", video.VideoPlaceholder.ToImageSource().ToString(), "cancel");
        }

        private void Button_Clicked_5(object sender, EventArgs e)
        {
            CrossMediaManager.Current.Pause();
        }

        private void Button_Clicked_6(object sender, EventArgs e)
        {
            CrossMediaManager.Current.Play();
        }

        private void Button_Clicked_7(object sender, EventArgs e)
        {
            CrossMediaManager.Current.StepForward();
        }

        private void Button_Clicked_8(object sender, EventArgs e)
        {
            CrossMediaManager.Current.StepBackward();
        }

        private void Button_Clicked_9(object sender, EventArgs e)
        {
            CrossMediaManager.Current.PlayNext();
        }

        private void Button_Clicked_10(object sender, EventArgs e)
        {
            CrossMediaManager.Current.PlayPrevious();
        }
    }
}

添加嵌入式资源

Xamarin.Forms学习之路——MediaManager Nuget学习_第5张图片

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <ProduceReferenceAssembly>true</ProduceReferenceAssembly>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>portable</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Plugin.MediaManager" Version="0.9.6" />
    <PackageReference Include="Plugin.MediaManager.Forms" Version="0.9.6" />
    <PackageReference Include="Xam.Plugin.SimpleAudioPlayer" Version="1.4.0" />
    <PackageReference Include="Xamarin.Forms" Version="4.3.0.908675" />
    <PackageReference Include="Xamarin.Essentials" Version="1.3.1" />
  </ItemGroup>
  
  <!--用完整路径-->
  <ItemGroup>
    <EmbeddedResource Include="SharedResource\demo.mp3" />
    <EmbeddedResource Include="SharedResource\demo2.mp3" />
  </ItemGroup>
  <!--不用完整路径 失败-->
  <!--<ItemGroup>
    <EmbeddedResource Include="SharedResource" />
  </ItemGroup>-->
</Project>

欢迎交流

本人入坑Xamarin.Forms刚不久,欢迎大家一起交流
QQ:1972353869

你可能感兴趣的:(Xamarin.Forms,UI设计,android,visual,studio,前端)