public void OnPrepared(AndroidMediaPlayer mp) { PlaybackSession.NaturalDuration = TimeSpan.FromMilliseconds(_player.Duration); VideoRatioChanged?.Invoke(this, (double)mp.VideoWidth / global::System.Math.Max(mp.VideoHeight, 1)); if (PlaybackSession.PlaybackState == MediaPlaybackState.Opening) { UpdateVideoStretch(_currentStretch); if (_isPlayRequested) { _player.Start(); PlaybackSession.PlaybackState = MediaPlaybackState.Playing; } else { // To display first image of media when setting a new source. Otherwise, last image of previous source remains visible _player.Start(); _player.Pause(); _player.SeekTo(0); } } _isPlayerPrepared = true; }
///<Summary> /// Set the current playback position (in seconds) ///</Summary> public void Seek(double position) { if (CanSeek) { player?.SeekTo((int)position * 1000); } }
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e) { base.OnElementChanged(e); if (Element == null) return; player = new MediaPlayer(); timer = new Timer(1000); timer.Elapsed += timer_Elapsed; player.Prepared += (sender, args) => { try { player.SeekTo(0); player.Start(); timer.Start(); } catch { } }; if (string.IsNullOrWhiteSpace(Player.Url)) return; InitPlayer(); }
public virtual void Stop() { if (PlaybackSession.PlaybackState == MediaPlaybackState.Playing || PlaybackSession.PlaybackState == MediaPlaybackState.Paused) { _player?.Pause(); // Do not call stop, otherwise player will need to be prepared again _player?.SeekTo(0); PlaybackSession.PlaybackState = MediaPlaybackState.None; } }
void OnPlaybackEnded(object sender, EventArgs e) { PlaybackEnded?.Invoke(sender, e); //this improves stability on older devices but has minor performance impact if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.M) { player.SeekTo(0); player.Stop(); player.Prepare(); } }
protected async override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.PodcastDetail); var showNumber = Intent.GetIntExtra("show_number", 0); episode = Activity1.ViewModel.GetPodcast(showNumber); var description = FindViewById<TextView>(Resource.Id.descriptionView); description.Text = episode.Description; var play = FindViewById<Button>(Resource.Id.playButton); var pause = FindViewById<Button>(Resource.Id.pauseButton); var stop = FindViewById<Button>(Resource.Id.stopButton); seekBar = FindViewById<SeekBar>(Resource.Id.seekBar1); status = FindViewById<TextView>(Resource.Id.statusText); updateHandler = new Handler(); player = new MediaPlayer(); player.SetDataSource(this, Android.Net.Uri.Parse(episode.AudioUrl)); player.PrepareAsync(); player.Prepared += (sender, e) => { initialized = true; player.SeekTo(timeToSet * 1000); UpdateStatus(); }; play.Click += (sender, e) => { player.Start(); updateHandler.PostDelayed(UpdateStatus, 1000); }; pause.Click += (sender, e) => player.Pause(); stop.Click += (sender, e) => { player.Stop(); player.Reset(); player.SetDataSource(this, Android.Net.Uri.Parse(episode.AudioUrl)); player.Prepare(); }; seekBar.ProgressChanged += (sender, e) => { if (!e.FromUser) return; player.SeekTo((int)(player.Duration * ((float)seekBar.Progress / 100.0))); }; var updated = await episode.GetTimeAsync(); if (updated == null || updated.ShowNumber != episode.ShowNumber) return; if (initialized && player != null) { player.SeekTo(updated.CurrentTime * 1000); UpdateStatus(); } else { timeToSet = updated.CurrentTime; } }
public string SoundPlay(string SoundName, string messageid, string messegeCondition, string status, string CurrentSliderValue) { try { if (SoundName == "served") { player = new Android.Media.MediaPlayer(); var ffd = Xamarin.Forms.Forms.Context.Assets.OpenFd("served.mp3"); player.Reset(); player.Prepared += (s, e) => { player.Start(); }; player.SetDataSource(ffd.FileDescriptor); player.Prepare(); } else { if (status == "Play") { player = new Android.Media.MediaPlayer(); player.Reset(); player.Prepared += (s, e) => { player.Start(); }; player.SetDataSource(SoundName); player.Prepare(); Messageid = messageid; if (messegeCondition == "right_audio") { TimerSound = new System.Timers.Timer(); TimerSound.Interval = 1000; TimerSound.Elapsed += TimerSound_Elapsed; TimerSound.Start(); } else { TimerSound = new System.Timers.Timer(); TimerSound.Interval = 1000; TimerSound.Elapsed += TimerSound_ElapsedSlider; TimerSound.Start(); } } else if (status == "Stop") { player.Stop(); TimerSound.Stop(); } else if (status == "Pause") { player.Pause(); TimerSound.Stop(); } else if (status == "PauseAfterplay") { try { var Converter = CurrentSliderValue.Substring(0, CurrentSliderValue.Length - 3);; int CurrentValue = 0; CurrentValue = Int32.Parse(Converter); player.SeekTo(CurrentValue); player.Start(); TimerSound.Start(); } catch (Exception) { } } } return(player.Duration.ToString()); } catch (Exception) { return(null); } }
/// <summary> /// Ons the start. /// </summary> /// <param name='intent'> Intent.</param> /// <param name='startId'>Start identifier.</param> public override void OnStart(Intent intent, int startId) { base.OnStart(intent, startId); stop(); episode = EpisodeList.SelectedEpisode; player = MediaPlayer.Create(PortaPodderApp.Context, Android.Net.Uri.Parse(PortaPodderDataSource.GetEpisodeLocation(episode))); // set the player to update the episode current position whenever a seek operation is sent player.SeekComplete += delegate(object sender, EventArgs e) { episode.PlayerPosition = player.CurrentPosition; }; // there is not duration meta-data to be had in the gpodder data structures, so we need to determine it once the media player has // been created and set it at this time and then broadcast it episode.Duration = player.Duration; // go to the last recorded position and start playing from there player.SeekTo(episode.PlayerPosition); player.Start(); // the progress monitor is the background thread which is going to send broadcasts about how far along the player is progressMonitor.Stop = false; if(!progressMonitor.IsRunning) { progressMonitor.Execute(); } // now bind an incoming message reciever for operations IntentFilter intentToReceiveFilter = new IntentFilter(); intentToReceiveFilter.AddAction(PLAYER_INSTRUCTION_SEEK_RELATIVE_FORWARD); intentToReceiveFilter.AddAction(PLAYER_INSTRUCTION_SEEK_RELATIVE_BACKWARD); intentToReceiveFilter.AddAction(PLAYER_INSTRUCTION_SEEK_ABSOLUTE); this.RegisterReceiver(reciever, intentToReceiveFilter, null, handler); receiversRegistered = true; }
public void reproducir(string downloadurl, bool desdecache) { // musicaplayer.SetDataSource(downloadurl); if (playeroffline.gettearinstancia() != null) { try { musicaplayer.Release(); musicaplayer = new MediaPlayer(); #pragma warning disable 414 if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.N) { musicaplayer.SetAudioAttributes(new AudioAttributes.Builder() .SetUsage(AudioUsageKind.Media) .SetContentType(AudioContentType.Music) .Build()); } else { #pragma warning disable CS0618 // El tipo o el miembro están obsoletos musicaplayer.SetAudioStreamType(Android.Media.Stream.Music); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos } #pragma warning restore 414 musicaplayer.SetWakeMode(this, WakeLockFlags.Partial); #pragma warning disable 414 #pragma warning disable CS0618 // El tipo o el miembro están obsoletos var focusResult = audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos #pragma warning restore 414 if (focusResult != AudioFocusRequest.Granted) { //could not get audio focus Console.WriteLine("Could not get audio focus"); } musicaplayer.Prepared += delegate { musicaplayer.Start(); if (this.desdecache) { musicaplayer.Pause(); } if (playeroffline.gettearinstancia() != null) { if (playeroffline.gettearinstancia().video.Visibility == ViewStates.Visible) { musicaplayer.SetDisplay(null); musicaplayer.SetDisplay(playeroffline.gettearinstancia().holder); } if (SettingsHelper.HasKey("posactual") && this.desdecache) { var posicion = 0; try { posicion = int.Parse(SettingsHelper.GetSetting("posactual")); musicaplayer.SeekTo(posicion); } catch (Exception) { } } } }; musicaplayer.Completion += delegate { playeroffline.gettearinstancia().RunOnUiThread(() => { playeroffline.gettearinstancia().RunOnUiThread(() => { playeroffline.gettearinstancia().siguiente.PerformClick(); }); }); }; musicaplayer.SetDataSource(this, Android.Net.Uri.Parse(downloadurl.Trim())); mostrarnotificacion(); musicaplayer.PrepareAsync(); } catch (Exception) { //if() playeroffline.gettearinstancia().RunOnUiThread(() => { Toast.MakeText(playeroffline.gettearinstancia(), "Error al reproducir", ToastLength.Long).Show(); }); } } else { musicaplayer.Reset(); StopSelf(); } }
public void OnPrepared( MediaPlayer mp ) { // now that the video is ready we can hide the progress bar ProgressBar.Visibility = ViewStates.Gone; MediaController.SetAnchorView( VideoPlayer ); // setup a seek listener mp.SetOnSeekCompleteListener( this ); // log the series they tapped on. MessageAnalytic.Instance.Trigger( MessageAnalytic.Watch, Name ); // if this is a new video, store the URL if ( App.Shared.Network.RockMobileUser.Instance.LastStreamingMediaUrl != MediaUrl ) { App.Shared.Network.RockMobileUser.Instance.LastStreamingMediaUrl = MediaUrl; VideoPlayer.Start( ); // once the video starts, if we're in landscape wide, go full screen if ( MainActivity.IsLandscapeWide( ) ) { ParentTask.NavbarFragment.ToggleFullscreen( true ); } } else { // otherwise, resume where we left off mp.SeekTo( (int)App.Shared.Network.RockMobileUser.Instance.LastStreamingMediaPos ); } }
public void OnPrepared( MediaPlayer mp ) { Rock.Mobile.Util.Debug.WriteLine( "OnPrepared - Audio ready to play" ); // now that we know the media player is read, set the controller's player MediaController.SetMediaPlayer( this ); MediaControllerPrepared = true; // setup a seek listener mp.SetOnSeekCompleteListener( this ); // log the series they tapped on. MessageAnalytic.Instance.Trigger( MessageAnalytic.Listen, Name ); // if this is a new video, store the URL if ( App.Shared.Network.RockMobileUser.Instance.LastStreamingMediaUrl != MediaUrl ) { App.Shared.Network.RockMobileUser.Instance.LastStreamingMediaUrl = MediaUrl; PlayerState = MediaPlayerState.Playing; mp.Start( ); SyncUI( ); } else { // otherwise, resume where we left off mp.SeekTo( (int)App.Shared.Network.RockMobileUser.Instance.LastStreamingMediaPos ); } }
public void OnCompletion(MediaPlayer mp) { mp.SeekTo (0); mp.Pause (); }
public void OnCompletion(MediaPlayer mediaPlayer) { mediaPlayer.SeekTo(0); }
public void reproducir(string downloadurl) { // musicaplayer.SetDataSource(downloadurl); if (YoutubePlayerServerActivity.gettearinstancia() != null) { musicaplayer.Release(); musicaplayer = new MediaPlayer(); if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.N) { musicaplayer.SetAudioAttributes(new AudioAttributes.Builder().SetUsage(AudioUsageKind.Media).SetContentType(AudioContentType.Music).Build()); } else { #pragma warning disable CS0618 // El tipo o el miembro están obsoletos musicaplayer.SetAudioStreamType(Android.Media.Stream.Music); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos } musicaplayer.SetWakeMode(this, WakeLockFlags.Partial); #pragma warning disable CS0618 // El tipo o el miembro están obsoletos var focusResult = audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos // musicaplayer.SetVideoScalingMode(VideoScalingMode.ScaleToFitWithCropping); if (focusResult != AudioFocusRequest.Granted) { //could not get audio focus Console.WriteLine("Could not get audio focus"); } musicaplayer.Error += (aa, aaaa) => { Console.WriteLine("klk aw aw aw"); }; musicaplayer.Info += (aa, aaa) => { var instancia = YoutubePlayerServerActivity.gettearinstancia(); if (instancia != null) { switch (aaa.What) { case MediaInfo.BufferingStart: if (instancia.prgBuffering.Visibility != ViewStates.Visible) { instancia.prgBuffering.Visibility = ViewStates.Visible; } break; case MediaInfo.BufferingEnd: if (instancia.prgBuffering.Visibility != ViewStates.Gone) { instancia.prgBuffering.Visibility = ViewStates.Gone; } break; case MediaInfo.VideoRenderingStart: if (instancia.prgBuffering.Visibility != ViewStates.Gone) { instancia.prgBuffering.Visibility = ViewStates.Gone; } break; } ; } }; musicaplayer.Prepared += delegate { if (YoutubePlayerServerActivity.gettearinstancia().videoon) { YoutubePlayerServerActivity.gettearinstancia().RunOnUiThread(() => { try { musicaplayer.SetDisplay(null); musicaplayer.SetDisplay(YoutubePlayerServerActivity.gettearinstancia().videoSurfaceHolder); } catch (Exception) { } YoutubePlayerServerActivity.gettearinstancia().SetVideoSize(); }); } musicaplayer.Start(); if (YoutubePlayerServerActivity.gettearinstancia().qualitychanged) { try { YoutubePlayerServerActivity.gettearinstancia().qualitychanged = false; musicaplayer.SeekTo(YoutubePlayerServerActivity.gettearinstancia().previousprogress); } catch (Exception) { } } }; musicaplayer.Completion += delegate { if ((musicaplayer.Duration > 5 && musicaplayer.CurrentPosition > 5)) { new Thread(() => { YoutubePlayerServerActivity.gettearinstancia().NextVideo(); }).Start(); } }; mostrarnotificacion(); musicaplayer.SetDataSource(this, Android.Net.Uri.Parse(downloadurl)); musicaplayer.PrepareAsync(); } else { musicaplayer.Reset(); StopSelf(); } }