Ejemplo n.º 1
0
 public MvxVideoPlayer(IRendererBuilder rendererBuilder)
 {
     _rendererBuilder = rendererBuilder;
     _player          = ExoPlayerFactory.NewInstance(RendererCount, 1000, 5000);
     _player.AddListener(this);
     _playerControl             = new PlayerControl(_player);
     _mainHandler               = new Handler();
     _listeners                 = new List <IListener>();
     _lastReportedPlaybackState = StateIdle;
     _rendererBuildingState     = RendererBuildingStateIdle;
     // Disable text initially.
     _player.SetSelectedTrack(TypeText, TrackDisabled);
 }
 public MvxVideoPlayer(IRendererBuilder rendererBuilder)
 {
     _rendererBuilder = rendererBuilder;
     _player = ExoPlayerFactory.NewInstance(RendererCount, 1000, 5000);
     _player.AddListener(this);
     _playerControl = new PlayerControl(_player);
     _mainHandler = new Handler();
     _listeners = new List<IListener>();
     _lastReportedPlaybackState = StateIdle;
     _rendererBuildingState = RendererBuildingStateIdle;
     // Disable text initially.
     _player.SetSelectedTrack(TypeText, TrackDisabled);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Properly cleanup of your player by releasing resources
        /// </summary>
        public override void OnDestroy()
        {
            var activityManager = (ActivityManager)this.ApplicationContext.GetSystemService(ActivityService);
            var lastTasks       = activityManager.GetRunningTasks(1);

            if (lastTasks?.FirstOrDefault() != null &&
                lastTasks.FirstOrDefault().TopActivity != null &&
                lastTasks.FirstOrDefault().TopActivity.PackageName != null &&
                lastTasks.FirstOrDefault().TopActivity.PackageName != "net.fildo.app")
            {
                Process.KillProcess(Process.MyPid());
            }
            base.OnDestroy();
            if (Player != null)
            {
                Player.Release();
                Player = null;
            }
        }
 /// <summary>
 /// For a good user experience we should account for when audio focus has changed.
 /// There is only one audio output there may be several media services trying to use it so
 /// we should act correctly based on this.  "duck" to be quiet and when we gain go full.
 /// All applications are encouraged to follow this, but are not enforced.
 /// </summary>
 /// <param name="focusChange"></param>
 public void OnAudioFocusChange(AudioFocus focusChange)
 {
     Log.Debug(TAG, "StreamingBackgroundService.OnAudioFocusChange() focusChange = " + focusChange);
     switch (focusChange)
     {
         case AudioFocus.Gain:
             Log.Debug(TAG, "AudioFocus.Gain");
             if (mediaPlayer == null)
             {
                 mediaPlayer = ExoPlayerFactory.NewInstance(1);
             }
             if (!IsPlaying)
             {
                 Play(source);
                 MessagingCenter.Send<PlayerStartedMessage>(new PlayerStartedMessage(), "PlayerStarted");
             }
             mediaPlayer.SendMessage(audioRenderer, MediaCodecAudioTrackRenderer.MsgSetVolume, 1.0f);
             break;
         case AudioFocus.Loss:
             Log.Debug(TAG, "AudioFocus.Loss");
             Stop();
             MessagingCenter.Send<PlayerStoppedMessage>(new PlayerStoppedMessage(), "PlayerStopped");
             break;
         case AudioFocus.LossTransient:
             Log.Debug(TAG, "AudioFocus.LossTransient");
             // We have lost focus for a short time, but likely to resume
             Stop();
             MessagingCenter.Send<PlayerStoppedMessage>(new PlayerStoppedMessage(), "PlayerStopped");
             break;
         case AudioFocus.LossTransientCanDuck:
             // We have lost focus but should till play at a muted 10% volume
             Log.Debug(TAG, "AudioFocus.LossTransientCanDuck");
             if (IsPlaying)
             {
                 mediaPlayer.SendMessage(audioRenderer, MediaCodecAudioTrackRenderer.MsgSetVolume, 0.1f);
             }
             break;
     }
 }
Ejemplo n.º 5
0
        private async void Play()
        {
            try
            {
                if ((CurrentTrack == null) && (CurrentTrackId == null))
                {
                    if (Queue.Count > 0)
                    {
                        Song firstOrDefault = Queue.FirstOrDefault();
                        if (firstOrDefault != null)
                        {
                            CurrentTrack   = firstOrDefault.Url;
                            CurrentTrackId = firstOrDefault.Id;
                        }
                        else
                        {
                            CurrentTrack   = null;
                            CurrentTrackId = null;
                        }
                    }
                    else
                    {
                        return;
                    }
                }

                Song currentSong = Queue.FirstOrDefault(p => p.Url == CurrentTrack);
                if (currentSong == null || CurrentTrack == null)
                {
                    currentSong = Queue.FirstOrDefault(p => p.Id == CurrentTrackId);
                }

                Player?.Stop();

                Player = null;

                if (this.paused && Player != null)
                {
                    this.paused = false;
                    //We are simply paused so just start again
                    Player.PlayWhenReady = true;
                    if (currentSong != null)
                    {
                        if (!string.IsNullOrEmpty(currentSong.Artist) && !string.IsNullOrEmpty(currentSong.Title))
                        {
                            this.StartForeground(currentSong.Artist + " - " + currentSong.Title);
                        }
                        else if (!string.IsNullOrEmpty(currentSong.Artist))
                        {
                            this.StartForeground(currentSong.Artist);
                        }
                        else if (!string.IsNullOrEmpty(currentSong.Title))
                        {
                            this.StartForeground(currentSong.Title);
                        }
                    }

                    this.RegisterRemoteClient();
                    this.remoteControlClient.SetPlaybackState(RemoteControlPlayState.Playing);
                    this.UpdateMetadata();
                    return;
                }

                if (Player == null)
                {
                    this.IntializePlayer();
                }

                if (Player.PlayWhenReady)
                {
                    this.Stop();
                }
                else
                {
                    //Player.Reset();
                    this.paused = false;
                    this.StopForeground(true);
                    this.ReleaseWifiLock();
                }

                this.starting = true;
                var netEase = Mvx.Resolve <INetEase>();
                var newSong = new SongNetease
                {
                    Artist = currentSong.Artist,
                    Title  = currentSong.Title,
                    Url    = CurrentTrack,
                    Id     = currentSong.Id
                };


                if (string.IsNullOrEmpty(newSong.Url))
                {
                    var tempsong = await netEase.GetSong(newSong.Id);

                    if (tempsong != null)
                    {
                        tempsong.Id     = newSong.Id;
                        tempsong.Title  = newSong.Title;
                        tempsong.Artist = newSong.Artist;
                        newSong         = tempsong;
                    }
                }


                var currenTrackToPlay = (await netEase.FixUrl(newSong, true)).Url;
                Dictionary <string, string> headers = new Dictionary <string, string>();
                if (currenTrackToPlay.StartsWith("http://221.228.64.228/"))
                {
                    headers.Add("Host", "m1.music.126.net");
                }
                headers.Add(
                    "User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");

                var trackUrl = Uri.Parse(currenTrackToPlay);
                FrameworkSampleSource sampleSource = new FrameworkSampleSource(Main, trackUrl, headers);

                TrackRenderer aRenderer = new MediaCodecAudioTrackRenderer(sampleSource, MediaCodecSelector.Default);

                if (QueueChanged != null)
                {
                    QueueChanged(this, new EventArgs());
                }

                var focusResult = this.audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
                if (focusResult != AudioFocusRequest.Granted)
                {
                    //could not get audio focus
                    Console.WriteLine("Could not get audio focus");
                }

                Player.Prepare(aRenderer);
                Player.PlayWhenReady = true;

                this.AquireWifiLock();

                if (currentSong != null)
                {
                    if (!string.IsNullOrEmpty(currentSong.Artist) && !string.IsNullOrEmpty(currentSong.Title))
                    {
                        this.StartForeground(currentSong.Artist + " - " + currentSong.Title);
                    }
                    else if (!string.IsNullOrEmpty(currentSong.Artist))
                    {
                        this.StartForeground(currentSong.Artist);
                    }
                    else if (!string.IsNullOrEmpty(currentSong.Title))
                    {
                        this.StartForeground(currentSong.Title);
                    }
                }

                this.RegisterRemoteClient();
                this.remoteControlClient.SetPlaybackState(RemoteControlPlayState.Buffering);
                this.UpdateMetadata();
            }
            catch
            {
                // ignored
            }
        }
Ejemplo n.º 6
0
        private void IntializePlayer()
        {
            Player = ExoPlayerFactory.NewInstance(1);

            //Tell our player to sream music
            //ExoPlayer.SetAudioStreamType(Stream.Music);

            //Wake mode will be partial to keep the CPU still running under lock screen
            //ExoPlayer.SetWakeMode(ApplicationContext, WakeLockFlags.Partial);

            //When we have prepared the song start playback

            /*ExoPlayer.Prepared += (sender, args) => {
             *  if (remoteControlClient != null)
             *  {
             *      remoteControlClient.SetPlaybackState(RemoteControlPlayState.Playing);
             *  }
             *  if (prepared != null)
             *  {
             *      prepared(this, 0);
             *  }
             *  UpdateMetadata();
             *  starting = false;
             *  Player.Start();
             * };*/
            //TODO EXOPLAYER

            Task.Run(
                async() =>
            {
                while (true)
                {
                    try
                    {
                        if ((posChanged != null) && (Player != null))
                        {
                            if (Player.CurrentPosition > 0 && Player.Duration > 0)
                            {
                                posChanged(this, Player.CurrentPosition);
                            }
                        }
                        if ((percentChanged != null) && (Player != null))
                        {
                            if (Player.CurrentPosition > 0 && Player.Duration > 0)
                            {
                                int percent = (int)(Player.CurrentPosition * 100 / Player.Duration);
                                percentChanged(this, percent);
                            }
                        }
                        await Task.Delay(100);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            });

            Player.AddListener(this);
            //When we have reached the end of the song stop ourselves, however you could signal next track here.

            /*
             * Player.Error += async (sender, args) =>
             * {
             *  Player.Reset();
             *  await Task.Delay(500);
             *  if (Player.IsPlaying)
             *  {
             *      return;
             *  }
             *  if (errorCounter <3)
             *  {
             *      errorCounter++;
             *      this.Play();
             *  }
             *  else
             *  {
             *      errorCounter = 0;
             *      if (remoteControlClient != null)
             *          remoteControlClient.SetPlaybackState(RemoteControlPlayState.Error);
             *      //playback error
             *      Console.WriteLine("Error in playback resetting: " + args.What);
             *      Stop();//this will clean up and reset properly.
             *      Next();
             *  }
             * };
             */
        }
 public MediaSessionConnectorPlaybackPreparer(IExoPlayer player, ConcatenatingMediaSource mediaSource)
 {
     _player      = player;
     _mediaSource = mediaSource;
 }
        private void Play(string source)
        {
            Log.Debug(TAG, "StreamingBackgroundService.Play()");

            var focusResult = audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
            Log.Debug(TAG, "StreamingBackgroundService.Play() RequestAudioFocus result: " + focusResult);
            if (focusResult == AudioFocusRequest.Granted)
            {
                if (mediaPlayer == null)
                {
                    mediaPlayer = ExoPlayerFactory.NewInstance(1);
                }

                RegisterReceiver(headphonesUnpluggedReceiver, new IntentFilter(AudioManager.ActionAudioBecomingNoisy));
                Log.Debug(TAG, "RegisterReceiver for headphones unplugged");

                String userAgent = ExoPlayerUtil.GetUserAgent (this, "ExoPlayerDemo");

                Android.Net.Uri soundString = Android.Net.Uri.Parse(source);
                var allocator = new DefaultAllocator(BUFFER_SEGMENT_SIZE);
                var dataSource = new DefaultUriDataSource(this, userAgent);
                ExtractorSampleSource sampleSource = new ExtractorSampleSource(soundString, dataSource, allocator,
                                                         BUFFER_SEGMENT_COUNT * BUFFER_SEGMENT_SIZE);
                audioRenderer = new MediaCodecAudioTrackRenderer (sampleSource, MediaCodecSelector.Default);

                mediaPlayer.Prepare(audioRenderer);
                mediaPlayer.PlayWhenReady = true;
                IsPlaying = true;
                AquireWifiLock();
                StartForeground();
            }
        }