Edit: You can do everything below or use the new Xamarin.Forms MediaElement
out of the box. Keep in mind that the MediaElement does not work yet with a StackLayout.
Mediaelement does not work within a stacklayout #2780
[Bug] MediaElement doesn't like being inside a StackLayout (particularly on Android)
In order to fix this and integrate looping in Xamarin Forms (assuming you followed the guide in the original post):
Add the code below to the end of the OnElementChanged() function
videoView.SetOnPreparedListener(new VideoLoop(videoView));
Create the videoloop class (I also wanted to loop)
using Android.Graphics;
using Android.Media;
using Android.Views;
using Android.Widget;
using YOURPROJECTHERE.Droid.FormsVideoLibrary;
using Java.Lang;
using System.Threading.Tasks;
namespace FormsVideoLibrary.Droid
{
public class VideoLoop : Java.Lang.Object, Android.Media.MediaPlayer.IOnPreparedListener
{
VideoView Video;
public VideoLoop(VideoView video)
{
Video = video;
Video.SetBackgroundColor(Android.Graphics.Color.White);
}
public void OnPrepared(MediaPlayer mp)
{
mp.SetOnInfoListener(new OnInfo(Video));
//Remove or comment the line below if you don't want to loop
mp.Looping = true;
mp.Start();
}
}
}
Now we make the background color transparent when the first frame is pushed (not at OnPrepared because it is still buffering at that point):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Media;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace YOURPOJECTNAMESPACE.Droid.FormsVideoLibrary
{
class OnInfo : Java.Lang.Object, Android.Media.MediaPlayer.IOnInfoListener
{
VideoView Video;
public OnInfo(VideoView video)
{
Video = video;
}
bool MediaPlayer.IOnInfoListener.OnInfo(MediaPlayer mp, MediaInfo what, int extra)
{
if (what == MediaInfo.VideoRenderingStart)
{
// video started; hide the placeholder.
Video.SetBackgroundColor(Android.Graphics.Color.Transparent);
return true;
}
return false;
}
}
}
I also added the below in the OnStopRequested function in the VideoRenderer class.
void OnStopRequested(object sender, EventArgs args)
{
videoView.StopPlayback();
videoView.SetBackgroundColor(Android.Graphics.Color.White);
}
And then finally back in the forms common project xaml.cs add the below on each page with a video:
protected override void OnAppearing()
{
xNAMEOFYOURVIDEO.Play();
xNAMEOFYOURVIDEO.Source = new ResourceVideoSource
{
Path = "yourfile.mp4"
};
}
protected override void OnDisappearing()
{
xNAMEOFYOURVIDEO.Stop();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…