protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Carega o layout "main" na view principal
			SetContentView (Resource.Layout.Main);

			// Pega o botão do recurso de layout e coloca um evento nele
			Button button = FindViewById<Button> (Resource.Id.button);

			vv = FindViewById<VideoView> (Resource.Id.video_view);
			pb = FindViewById<ProgressBar> (Resource.Id.progress_bar);
			MediaController mc = new MediaController(this);
			mp = new MediaPlayer ();

			pb.SetOnTouchListener (this);

			var uri = Android.Net.Uri.Parse ("http://3gpfind.com/vid/load/Movie%20Trailer/Predators(3gpfind.com).3gp");
			vv.SetOnPreparedListener (this);
			vv.SetVideoURI(uri);
			vv.SetMediaController(mc);
			mc.SetMediaPlayer(vv);
			mc.SetAnchorView(vv);

			button.Click += delegate {
				mc.Show();
				if (!ready)
				{
					holder = vv.Holder;
					holder.SetType (SurfaceType.PushBuffers);
					holder.AddCallback(this);
					mp.SetDataSource(this, uri);
					mp.SetOnPreparedListener(this);
					mp.Prepare();
					ready = true;
				}

				mp.Start();
//				vv.Start();

				Toast.MakeText (this, "Video Started", ToastLength.Short).Show ();
			};
		}
Beispiel #2
0
        private void SetVideoSource(Uri uri)
        {
            if (!uri.IsAbsoluteUri || uri.Scheme == "")
            {
                uri = new Uri(MsAppXScheme + ":///" + uri.OriginalString.TrimStart("/"));
            }

            var isResource = uri.Scheme.Equals(MsAppXScheme, StringComparison.OrdinalIgnoreCase) ||
                             uri.Scheme.Equals(MsAppDataScheme, StringComparison.OrdinalIgnoreCase);

            if (isResource)
            {
                var filename = global::System.IO.Path.GetFileName(uri.LocalPath);
                var afd      = Application.Context.Assets.OpenFd(filename);
                _player.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
                return;
            }

            if (uri.IsFile)
            {
                _player.SetDataSource(Application.Context, Android.Net.Uri.Parse(uri.PathAndQuery));
                return;
            }

            _player.SetDataSource(Application.Context, Android.Net.Uri.Parse(uri.ToString()));
        }
        ///<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());
        }
Beispiel #4
0
 public void Play(string p_FilePath)
 {
     using (MediaPlayer player = new MediaPlayer()) {
         if (p_FilePath.IndexOf ("Content") > -1) {
             Android.Content.Res.AssetFileDescriptor af = Android.App.Application.Context.Assets.OpenFd (p_FilePath);
             player.SetDataSource (af.FileDescriptor, af.StartOffset, af.Length);
         } else {
             player.SetDataSource (Path.Combine(DataPath,p_FilePath));
         }
         player.Prepare ();
         player.Start ();
     }
 }
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            nn_surface = new Surface (surface);

            RelativeLayout.LayoutParams l;
            DisplayMetrics metrics = new DisplayMetrics();
            nn_activity.WindowManager.DefaultDisplay.GetMetrics(metrics);
            l = new RelativeLayout.LayoutParams(metrics.HeightPixels, metrics.WidthPixels);
            l.AddRule(LayoutRules.CenterInParent);
            float scale = (metrics.HeightPixels * 1.0f) / (metrics.WidthPixels * 1.0f);
            textureview.ScaleX = scale;
            textureview.LayoutParameters=l;

            try {
                nn_mediaplayer= new MediaPlayer();
                //String uriPath = "android.resource://"+nn_activity.PackageName+"/raw/Tap5050_About";
                nn_mediaplayer.SetDataSource(nn_activity,global::Android.Net.Uri.Parse("android.resource://"+nn_activity.PackageName +"/"+ Resource.Raw.Tap5050_About));
                nn_mediaplayer.SetSurface(nn_surface);
                nn_mediaplayer.Prepare();
                nn_mediaplayer.Prepared+= (object sender, EventArgs e) => {
                    (sender as MediaPlayer).Start ();
                };
                nn_mediaplayer.Completion+= (object sender, EventArgs e) => {
                    (sender as MediaPlayer).SeekTo (0);
                    (sender as MediaPlayer).Pause ();
                };

            }catch(Exception e){
                Toast.MakeText (nn_activity,"Sorry,Can not play the video",ToastLength.Long).Show();
            }
        }
        public Task PlaySoundAsync(string filename)
        {
            // Create media player
            var player = new MediaPlayer();

            // Create task completion source to support async/await
            var tcs = new TaskCompletionSource<bool> ();

            // Open the resource
            var fd = Xamarin.Forms.Forms.Context.Assets.OpenFd (filename);

            // Hook up some events
            player.Prepared += (s, e) => {
                player.Start();
            };

            player.Completion += (sender, e) => {
                tcs.SetResult(true);
            };

            // Initialize
            player.SetDataSource (fd.FileDescriptor);
            player.Prepare ();

            return tcs.Task;
        }
		private void PlayVideo(SurfaceTexture surfaceTexture)
		{
			DoCleanUp();
			try
			{

				path = "http://qthttp.apple.com.edgesuite.net/1010qwoeiuryfg/sl.m3u8";
				if (path == "")
				{
					// Tell the user to provide a media file URL.
					Toast.MakeText(this, "Please edit MediaPlayerDemo_setSurface Activity, " + "and set the path variable to your media file path." + " Your media file must be stored on sdcard.", ToastLength.Long).Show();
					return;
				}
				// Create a new media player and set the listeners
				mMediaPlayer = new MediaPlayer(this, true);
				mMediaPlayer.SetDataSource(path);
				if (surf == null)
				{
					surf = new Surface (surfaceTexture);
				}
				mMediaPlayer.SetSurface(surf);
				mMediaPlayer.PrepareAsync();
				mMediaPlayer.SetOnBufferingUpdateListener(this);
				mMediaPlayer.SetOnCompletionListener(this);
				mMediaPlayer.SetOnPreparedListener(this);
				VolumeControlStream = Stream.Music;

			}
			catch (Exception e)
			{
				Log.Error(TAG, "error: " + e.Message, e);
			}
		}
 /// <summary>
 /// Method that plays the sound on Android.
 /// </summary>
 public void PlaySound(SoundboardItem item)
 {
     player = new MediaPlayer ();
     var fd = Xamarin.Forms.Forms.Context.Assets.OpenFd (item.FileName + ".mp3");
     player.SetDataSource (fd.FileDescriptor);
     player.Prepare ();
     player.Start ();
 }
 public override void Play(string filename)
 {
     AssetFileDescriptor afd = Assets.OpenFd(filename);
     player = new MediaPlayer();
     player.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
     player.Completion += DidFinishPlaying;
     player.Prepare();
     player.Start();
 }
 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;
 }
Beispiel #11
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;
 }
Beispiel #12
0
        public Media_player(File file)
        {
            music_File = file;

            if (isPlay)
            {
                Dispose();
            }

            player = new Android.Media.MediaPlayer();
            player.SetDataSource(music_File.AbsolutePath);
            player.Prepare();
        }
		void play(string fullPath)
		{
			ISurfaceHolder holder = videoView.Holder;
			holder.SetType (SurfaceType.PushBuffers);
			holder.AddCallback( this );
			player = new  MediaPlayer ();
			Android.Content.Res.AssetFileDescriptor afd = this.Assets.OpenFd(fullPath);
			if  (afd != null )
			{
				player.SetDataSource (afd.FileDescriptor, afd.StartOffset, afd.Length);
				player.Prepare ();
				player.Start ();
			}
		}
Beispiel #14
0
 public AndroidMusic(AssetFileDescriptor afd)
 {
     this.mp = new MediaPlayer ();
     try {
         mp.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
         mp.Prepare();
         isPrepared = true;
         mp.SetOnCompletionListener(this);
         mp.SetOnSeekCompleteListener(this);
         mp.SetOnPreparedListener(this);
         mp.SetOnVideoSizeChangedListener(this);
     } catch {
         throw new ApplicationException("Couldn't load music");
     }
 }
		public void PlayAudioFile(string fileName)
		{
			var player = new MediaPlayer();
			var fd = global::Android.App.Application.Context.Assets.OpenFd(fileName);
			player.Prepared += (s, e) =>
			{
				player.Start();
			};

			player.Completion += (s, e) =>
			{
			};

			player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
			player.Prepare();
		}
Beispiel #16
0
        public void StartVideoPlayback(SurfaceView surface, string FilePath)
        {
            if (_player != null)
              {
            StopVideoPlayback();
              }
              _player = new MediaPlayer();

              ISurfaceHolder holder = surface.Holder;
              holder.SetType(Android.Views.SurfaceType.PushBuffers);
              holder.SetFixedSize(400, 300);

              _player.SetDisplay(holder);
              _player.SetDataSource(FilePath);
              _player.Prepare();
              _player.Start();
        }
 public void playAudio(string filePath)
 {
     if (player == null)
     {
         player = new MediaPlayer();
         player.SetDataSource(filePath);
         player.Prepare();
         player.Start();
     }
     else
     {
         player.Reset();
         player.SetDataSource(filePath);
         player.Prepare();
         player.Start();
     }
     isPlaying = true;
 }
Beispiel #18
0
        public AndroidMusic(AssetFileDescriptor assetDescriptor)
        {
            mediaPlayer = new MediaPlayer();
            try
            {
                mediaPlayer.SetDataSource(assetDescriptor.FileDescriptor,
                                          assetDescriptor.StartOffset,
                                          assetDescriptor.Length);
                mediaPlayer.Prepare();
                isPrepared = true;
                mediaPlayer.SetOnCompletionListener(this);
                mediaPlayer.SetOnSeekCompleteListener(this);
                mediaPlayer.SetOnPreparedListener(this);
                mediaPlayer.SetOnVideoSizeChangedListener(this);

            }
            catch (Exception e)
            {
                throw new SystemException("Couldn't load music");
            }
        }
Beispiel #19
0
 public Sound(string filename, float volume, bool looping)
 {
     this._player = new MediaPlayer();
     // get the Asset Descriptor and Release it when the SetDataSource returns
     // otherwise you cant play the file
     using (AssetFileDescriptor fd = Game.contextInstance.Assets.OpenFd(filename))
     {
         _player.SetDataSource(fd.FileDescriptor);
     }
     _player.Prepared += this.OnPrepared;
     this.Looping = looping;
     this.Volume = volume;
     // prepare on the background  thread
     try
     {
         _player.PrepareAsync();
     }
     catch (Exception ex)
     {
         Log.Debug("MonoGameInfo", ex.ToString());
     }
 }
 internal void ProcessPlay()
 {
     DrawCommon("XXXXX");
     if (smf_music == null)
         return;
     if (media_player == null) {
         try {
             media_player = new MediaPlayer ();
             media_player.SetDataSource(jetfile.FullName);
             media_player.Prepare();
         } catch (IOException ex) {
             media_player = null;
             DrawCommon ("failed to load SMF");
             return;
         }
     }
     if (midi_player == null) {
         midi_player = new MidiPlayer (smf_music);
         midi_player.Finished += delegate { StopViews(); };
         midi_player.MessageReceived += HandleSmfMessage;
     }
     // This state check is not necessary for MidiPlayer,
     // but for JetPlayer (which does not expose state).
     if (midi_player.State != PlayerState.Playing) {
         midi_player.PlayAsync();
         media_player.Start();
     }
     DrawCommon ("PLAY");
 }
        //Used for entering the Mandarin_ma speech processing screen
        void HandleMandarin_Ma_Male_Select()
        {
            SetContentView (Resource.Layout.Mandarin_Mother_Male);

            string RecordPath = "/sdcard/Recording.mp3";
            //string RecordPath = Environment.getExternalStorageDirectory ()
            //	.getAbsolutePath () + "/Recording.mp3";

            //string RecordPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Recording.3gpp";
            //string RecordPath = this.file.getAbsolutePath().substring(8)

            Button PlayStock = FindViewById<Button> (Resource.Id.PlayMa);
            PlayBack = FindViewById<Button> (Resource.Id.PlayBack);
            Button BackToMandarin = FindViewById<Button> (Resource.Id.BackToMandarin);

            RecordVoice = FindViewById<Button> (Resource.Id.Record);
            StopRecord = FindViewById<Button> (Resource.Id.Stop);
            StockPlayer = MediaPlayer.Create(this, Resource.Raw.mother);

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

            //Click Event Handlers
            PlayStock.Click += delegate {
                StockPlayer.Start();
            };

            RecordVoice.Click += delegate {

                RecordVoice.Enabled = !RecordVoice.Enabled;
                StopRecord.Enabled = !StopRecord.Enabled;
                if (PlayBack.Enabled==true){
                    PlayBack.Enabled = false;
                }

                _recorder.SetAudioSource (AudioSource.Mic);
                _recorder.SetOutputFormat (OutputFormat.Mpeg4);
                _recorder.SetOutputFile(RecordPath);
                _recorder.SetAudioEncoder (AudioEncoder.Aac);

                _recorder.Prepare();
                _recorder.Start ();

            };

            //Stops recording
            StopRecord.Click += delegate {
                StopRecord.Enabled =! StopRecord.Enabled;

                if (PlayBack.Enabled==false){
                    PlayBack.Enabled = true;
                }

                _recorder.Stop ();
                _recorder.Reset ();

                /* For instant playback
                _player.SetDataSource (RecordPath);
                _player.Prepare ();
                _player.Start ();
                */
                RecordVoice.Enabled = !RecordVoice.Enabled;

            };

            PlayBack.Click += delegate {
                RecordPlayer = new MediaPlayer ();
                RecordPlayer.SetDataSource (RecordPath);
                RecordPlayer.Prepare ();
                RecordPlayer.Start ();

            };

            BackToMandarin.Click += delegate {
                HandleMandarinSelect ();
            };
        }
        void InitBeepSound()
        {
            if(playBeep && mediaPlayer == null)
            {
                VolumeControlStream = Android.Media.Stream.Music;
                mediaPlayer = new MediaPlayer();
                mediaPlayer.SetAudioStreamType(Android.Media.Stream.Music);
                mediaPlayer.SetOnCompletionListener(beepListener);

                var file = Resources.OpenRawResourceFd(BeepResource);
                try{
                    mediaPlayer.SetDataSource(file.FileDescriptor, file.StartOffset, file.Length);

                    file.Close();
                    mediaPlayer.SetVolume(0.1f, 0.1f);
                    mediaPlayer.Prepare();
                }
                catch(Java.IO.IOException e)
                {
                    mediaPlayer = null;
                }
            }
        }
		void PlaySound (string customSound)
		{
			if (_ringtone != null) {
				return;
			}           

//			_ringtone = RingtoneManager.GetRingtone (Application.Context, sound);
//			_ringtone.Play ();

			try {
				var sound = GetRingtoneUri (customSound);

				_ringtone = new MediaPlayer ();
				_ringtone.SetDataSource (this, sound);

				_ringtone.SetAudioStreamType (Stream.Alarm);

				_ringtone.Looping = true;
				_ringtone.Prepare ();
				_ringtone.Start ();
			} catch {
			}   
		}
Beispiel #24
0
        public override void OnCreate()
        {
            base.OnCreate();
              mediaPlayer = new MediaPlayer();
              mediaPlayer.SetAudioStreamType(Stream.Music);
              mediaPlayer.SetDataSource(StreamAddress);

              mediaPlayer.Prepared += MediaPlayerPrepared;

              mediaSession = new MediaSession(this, PackageName);

              notificationManager = (NotificationManager)GetSystemService(NotificationService);
        }
        void play(string fullPath)
        {
            ISurfaceHolder holder = _tv.Holder;
            holder.SetType (SurfaceType.PushBuffers);
            // Necesito saber cuando la superficie esta creada para poder asignar el Display al MediaPlayer
            holder.AddCallback (this);
            _player = new MediaPlayer();

            Android.Content.Res.AssetFileDescriptor afd = this.Assets.OpenFd(fullPath);
            if (afd != null)
            {
            _player.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
            _player.Prepare ();

            _player.Start();
            }
        }
    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;
      }
    }
		private void PlayVideo(int Media)
		{
			DoCleanUp();
			try
			{

				switch (Media)
				{
				case LOCAL_VIDEO:
					//                
					//				 * TODO: Set the path variable to a local media file path.
					//				 
					path = "http://172.16.101.100:81/video/123.mp4";
					if (path == "")
					{
						// Tell the user to provide a media file URL.
						Toast.MakeText(this, "Please edit MediaPlayerDemo_Video Activity, " + "and set the path variable to your media file path." + " Your media file must be stored on sdcard.", ToastLength.Long).Show();
						return;
					}
					break;
				case STREAM_VIDEO:
					//                
					//				 * TODO: Set path variable to progressive streamable mp4 or
					//				 * 3gpp format URL. Http protocol should be used.
					//				 * Mediaplayer can only play "progressive streamable
					//				 * contents" which basically means: 1. the movie atom has to
					//				 * precede all the media data atoms. 2. The clip has to be
					//				 * reasonably interleaved.
					//				 * 
					//				 
						path = "http://172.16.101.100:81/video/123.mp4";
					if (path == "")
					{
						// Tell the user to provide a media file URL.
						Toast.MakeText(this, "Please edit MediaPlayerDemo_Video Activity," + " and set the path variable to your media file URL.", ToastLength.Long).Show();
						return;
					}

					break;

				}

				// Create a new media player and set the listeners
				mMediaPlayer = new MediaPlayer(this);
				mMediaPlayer.SetDataSource(path);
				mMediaPlayer.SetDisplay(holder);
				mMediaPlayer.PrepareAsync();
				mMediaPlayer.SetOnBufferingUpdateListener(this);
				mMediaPlayer.SetOnCompletionListener(this);
				mMediaPlayer.SetOnPreparedListener(this);
				mMediaPlayer.SetOnVideoSizeChangedListener(this);
				VolumeControlStream = Stream.Music;

			}
			catch (Exception e)
			{
				Log.Error(TAG, "error: " + e.Message, e);
			}
		}
        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();
            }
        }
Beispiel #29
0
        public static Sound Create(string assetPath, float volume, bool looping)
        {
            MediaPlayer player = new MediaPlayer();
            Sound sound = new Sound(player);

            player.SetDataSource(Game.contextInstance.Assets.OpenFd(assetPath).FileDescriptor);
            player.Prepared += sound.OnPrepared;
            sound.Looping = looping;
            sound.Volume = volume;
            
            Sound.Enqueue(player.Prepare);

            return sound;
        }
Beispiel #30
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();
            }
        }
Beispiel #32
0
        public static Sound Create(string assetPath, float volume, bool looping)
        {
            MediaPlayer player = new MediaPlayer();
            Sound sound = new Sound(player);
            //This breaks the platformer sample. Not sure if it works anywhere else
            //player.SetDataSource(Game.contextInstance.Assets.OpenFd(assetPath).FileDescriptor);
            player.SetDataSource(assetPath);
            player.Prepared += sound.OnPrepared;
            sound.Looping = looping;
            sound.Volume = volume;

            Sound.Enqueue(player.Prepare);

            return sound;
        }