我为iOS和Android制作应用程序,提供观看视频的能力。我目前正在开发iOS实现,但每次我解除持有AVPlayer或MPPlayer的viewcontroller时,应用程序抛出'System.InvalidOperationException:Sequence不包含匹配元素'。我不知道为什么会这样。我会分享一些示例代码。
渲染
using AnimeViewer.iOS.CustomRenderers;
using AnimeViewer.Views.Partials;
using AVFoundation;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(VideoPlayer), typeof(VideoPlayerRenderer))]
namespace AnimeViewer.iOS.CustomRenderers
{
public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, UIView>
{
public VideoPlayer VideoPlayer { get; set; }
protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> e)
{
base.OnElementChanged(e);
if (e.NewElement == null) return;
VideoPlayer = e.NewElement;
SetNativeControl(new UIView {Frame = UIScreen.MainScreen.Bounds});
var player = new AVPlayer(new NSUrl(VideoPlayer.Source));
var playerLayer = new AVPlayerLayer
{
Player = player,
Frame = Control.Frame
};
Control.Layer.AddSublayer(playerLayer);
player.Play();
}
}
}
查看
<?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:partials="clr-namespace:AnimeViewer.Views.Partials;assembly=AnimeViewer"
x:Class="AnimeViewer.Views.VideoPlayerPage">
<partials:VideoPlayer x:Name="Player"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
</ContentPage>
答案 0 :(得分:0)
您不需要自定义渲染器来调用视频播放器,您可以使用DependencyService:
public class VideoPLayer : IVideoPlayer
{
public void Play(string path)
{
var _player = new AVPlayer(NSUrl.FromFilename(path));
var _playerController = new AVPlayerViewController();
_playerController.Player = _player;
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
while (vc.PresentedViewController != null)
{
vc = vc.PresentedViewController;
}
vc.PresentViewController(_playerController, true, null);
_playerController.View.Frame = vc.View.Frame;
}
}
要了解有关DependencyService的更多信息,您可以访问以下链接:https://developer.xamarin.com/guides/xamarin-forms/dependency-service/