我在主页上有一个列表视图,当我单击列表视图时,它会转到第二页,该页面与Exoplayer集成了自定义渲染器,因此问题在于如何正确释放播放器,因为当前_player始终等于null,多个播放音频,如果多次从第一页导航到第二页。
这是自定义渲染器的代码-
public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, SimpleExoPlayerView>, IExoPlayerEventListener
{
private SimpleExoPlayerView _playerView;
private SimpleExoPlayer _player;
private DefaultTrackSelector trackSelector;
DefaultHttpDataSourceFactory defaultHttpDataSourceFactory;
DefaultDataSourceFactory defaultDataSourceFactory ;
ExtractorMediaSource extractorMediaSource ;
public VideoPlayerRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> e)
{
base.OnElementChanged(e);
if (_player == null)
{
InitializePlayer();
}
Play();
}
private void InitializePlayer()
{
trackSelector = new DefaultTrackSelector();
_player = ExoPlayerFactory.NewSimpleInstance(Context,trackSelector);
_player.PlayWhenReady = true;
_playerView = new SimpleExoPlayerView(Context) { Player = _player };
SetNativeControl(_playerView);
SetBackgroundColor(Android.Graphics.Color.Green);
}
private void Play()
{
Uri sourceUri = Uri.Parse(Element.SourceUrl);
var mediaUri = Android.Net.Uri.Parse(Element.SourceUrl);
var userAgent = Util.GetUserAgent(Context, "App1");
defaultHttpDataSourceFactory = new DefaultHttpDataSourceFactory(userAgent);
defaultDataSourceFactory = new DefaultDataSourceFactory(Context, null, defaultHttpDataSourceFactory);
extractorMediaSource = new ExtractorMediaSource(mediaUri, defaultDataSourceFactory, new DefaultExtractorsFactory(), null, null);
_player.Prepare(extractorMediaSource);
_player.AddListener(this);
}
答案 0 :(得分:0)
在您的自定义渲染器中,覆盖OnDetachedFromWindow
以停止播放器:
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
_player.Stop();
_player.Release();
}
更新:
要控制播放器,您应该创建一个SimpleExoPlayer
的单例,并确保整个项目中只有一个_player
:
class ExoPlayerInstance
{
private static SimpleExoPlayer _player;
public static SimpleExoPlayer player
{
get
{
if (_player == null)
{
_player = ExoPlayerFactory.NewSimpleInstance(Application.Context, new DefaultTrackSelector());
_player.PlayWhenReady = true;
}
return _player;
}
}
}
然后在您的自定义渲染中,删除InitializePlayer
部分并使用ExoPlayerInstance
:
protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> e)
{
base.OnElementChanged(e);
//remove the InitializePlayer part
//if (_player == null)
// InitializePlayer();
_player = ExoPlayerInstance.player;
_playerView = new SimpleExoPlayerView(Context) { Player = _player };
SetNativeControl(_playerView);
if (_player.IsPlayingAd || _player.IsLoading)
{
//maybe something more need to do , stop() here is an example
_player.Stop();
}
Play();
}