///<Summary>
        /// Load wav or mp3 audio file as a stream
        ///</Summary>
        public bool Load(Stream audioStream)
        {
            player.Reset();

            DeleteFile(path);

            //cache to the file system
            path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), $"cache{index++}.wav");
            var fileStream = File.Create(path);

            audioStream.CopyTo(fileStream);
            fileStream.Close();

            try
            {
                player.SetDataSource(path);
            }
            catch
            {
                try
                {
                    var context = Android.App.Application.Context;
                    player?.SetDataSource(context, Uri.Parse(Uri.Encode(path)));
                }
                catch
                {
                    return(false);
                }
            }

            return(PreparePlayer());
        }
        public void StartPlayer(AssetFileDescriptor filePath)
        {
            if (player == null)
            {
                player = new MediaPlayer();
                player.Reset();
                /*

                player.SetDataSource(filePath.FileDescriptor, filePath.StartOffset, filePath.Length);
                player.Prepare();
                player.Start();
                 * */

            }
            if(player != null)
            {
                //player.Reset();
                player.SetDataSource(filePath.FileDescriptor, filePath.StartOffset, filePath.Length);
                player.Prepare();
                if (AudioPosition > 0)
                {
                   player.SeekTo(AudioPosition);
                }
                player.Start();
            }
        }
		public void InitAndPlayAudio (string trackSource)
		{
			var resourceId = GetRawResourceId(trackSource);
			Console.WriteLine("Resource id for " + trackSource + " = " 
				+ (resourceId.HasValue ? resourceId.Value.ToString() : "(null)"));


			if (player != null) {
				if (player.IsPlaying) {
					player.Stop ();
				}
				player.Reset ();
				player.Release ();
				player = null;
			}

			if (resourceId.HasValue) {
				player = MediaPlayer.Create (Application.Context, resourceId.Value);

				// do not use player.Prepare () -- MediaPlayer.Create takes care of this

				player.Completion += (sender, e) => {
					player.Reset ();
					player.Release ();
					player = null;
					AudioState = AudioState.Stopped;
				};

				AudioState = AudioState.Playing;
				player.Start ();
			}
		}
Esempio n. 4
0
        protected override void OnResume()
        {
            base.OnResume ();

            _recorder = new MediaRecorder ();
            _player = new MediaPlayer ();

            _player.Completion += (sender, e) => {
                _player.Reset ();
                _start.Enabled = !_start.Enabled;
            };
        }
Esempio n. 5
0
 public int findDuration(string filename)
 {
     MediaPlayer wav = new MediaPlayer();
     FileInputStream fs = new FileInputStream(filename);
     FileDescriptor fd = fs.FD;
     wav.SetDataSource(fd);
     wav.Prepare();
     int length = wav.Duration;
     wav.Reset();
     wav.Release();
     return length;
 }
Esempio n. 6
0
 public int videoDuration(string filename)
 {
     MediaPlayer video = new MediaPlayer();
     FileInputStream fs = new FileInputStream(filename);
     FileDescriptor fd = fs.FD;
     video.SetDataSource(fd);
     video.Prepare();
     int length = video.Duration;
     video.Reset();
     video.Release();
     return length;
 }
Esempio n. 7
0
        public void Resume()
        {
            //base.OnResume();

            _recorder = new MediaRecorder();
            _player = new MediaPlayer();

            _player.Completion += (sender, e) =>
            {
                _player.Reset();

                MessagingCenter.Send<ISoundRecorder>(this, "MediaPlayer.Complete");
            };
        }
Esempio n. 8
0
        protected override void OnResume()
        {
            base.OnResume();

            _recorder = new MediaRecorder();
            _player = new MediaPlayer();

            _player.Completion += (sender, e) =>
            {
                _player.Reset();
                _btnRecord.Enabled = true;
                _btnPlay.Enabled = true;
            };
        }
Esempio n. 9
0
 public void OnCompletion(MediaPlayer player)
 {
     try
     {
         player.Stop();
         player.Reset();
         player.Release();
     } catch (Exception ex)
     {
         #if DEBUG
         System.Diagnostics.Debug.WriteLine("Exception in audio {0}", ex.Message);
         #endif
     }
 }
Esempio n. 10
0
        public void OnCompletion(AndroidMediaPlayer mp)
        {
            MediaEnded?.Invoke(this, null);
            PlaybackSession.PlaybackState = MediaPlaybackState.None;

            // Play next item in playlist, if any
            if (_playlistItems != null && _playlistIndex < _playlistItems.Count - 1)
            {
                _player.Reset();
                SetVideoSource(_playlistItems[++_playlistIndex]);
                _player.Prepare();
                _player.Start();
            }
        }
Esempio n. 11
0
        public async override void play(bool alone)
        {
            try
            {
                setStemSounds();
                string soundResult = propStemSounds[(propValue / 10) - 1];
                if (alone == false)
                {
                    soundResult = propStemSounds[9 + (propValue / 10) - 1];
                }

                if (player == null)
                {
                    player = player ?? new MediaPlayer();
                }
                else
                {
                    player.Reset();
                }

                new System.Threading.Thread(async() => {
                    await player1.SetDataSourceAsync(soundResult);

                    player1.Prepare();
                    player1.Start();
                }).Start();

                byte[] TotalBytes  = System.IO.File.ReadAllBytes(soundResult);
                double bitrate     = (BitConverter.ToInt32(new[] { TotalBytes[28], TotalBytes[29], TotalBytes[30], TotalBytes[31] }, 0) * 8);
                double duration    = (TotalBytes.Length - 8) * 8 / bitrate;
                int    durationInt = Convert.ToInt32(duration * 1000);
                System.Threading.Thread.Sleep(durationInt);

                if (player1 == null)
                {
                    player1 = player1 ?? new MediaPlayer();
                }
                else
                {
                    player1.Reset();
                }

                await player.SetDataSourceAsync(soundResult);

                //player.Prepare();
                //player.Start();
            }
            catch (Exception e)
            { }
        }
                public bool OnError( MediaPlayer mp, MediaError error, int extra )
                {
                    ProgressBar.Visibility = ViewStates.Gone;

                    // only show the resultView if we're active.
                    if( FragmentActive == true )
                    {
                        ResultView.Show( MessagesStrings.Error_Title, 
                            PrivateControlStylingConfig.Result_Symbol_Failed, 
                            MessagesStrings.Error_Watch_Playback,
                            GeneralStrings.Retry );
                        
                        ResultView.SetBounds( new System.Drawing.RectangleF( 0, 0, NavbarFragment.GetFullDisplayWidth( ), this.Resources.DisplayMetrics.HeightPixels ) );
                    }

                    if( mp != null )
                    {
                        mp.Stop( );
                        mp.Reset( );
                    }

                    MediaControllerPrepared = false;

                    PlayerState = MediaPlayerState.None;

                    //SyncUI( );

                    return true;
                }
Esempio n. 13
0
        protected override void OnResume()
        {
            base.OnResume ();
            _recorder = new MediaRecorder ();
            _player = new MediaPlayer ();

            _player.Completion += (sender, e) => {
                _player.Reset ();

            };

            _photoAdapter.NotifyDataSetChanged ();
            _recordAdapter.NotifyDataSetChanged ();
        }
        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();
            }
        }
Esempio n. 15
0
    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;
      }
    }
Esempio n. 16
0
        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);
            }
        }
        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();
            }
        }