private void RequestListener_TripUpdates(object sender, CreateRequestEventListener.TripUpdatesEventArgs e)
 {
     if (e.Status == "accepted")
     {
         tripStatusText.Text = "Coming";
         mapHelper.UpdateDriverlocationToPickup(e.DriverLocation, pickuplocationLatLng);
     }
     else if (e.Status == "arrived")
     {
         tripStatusText.Text = "Arrived";
         mapHelper.UpdateDriverArrived();
         //
         AVAudioPlayer player = AVAudioPlayer.FromUrl(NSUrl.FromFilename("Sounds/alertios.aiff"));
         player.PrepareToPlay();
         player.Play();
     }
     else if (e.Status == "ontrip")
     {
         tripStatusText.Text = "On Trip";
         mapHelper.UpdateLocationToDestination(e.DriverLocation, destinationLatLng);
     }
     else if (e.Status == "ended")
     {
         faresAmountText.Text   = "$" + e.Fares.ToString();
         overlay.Hidden         = false;
         makePaymentView.Hidden = false;
         UIView.Animate(0.2, HideTripControlPanel);
         makePaymentButton.TouchUpInside += (i, args) =>
         {
             overlay.Hidden         = true;
             makePaymentView.Hidden = true;
             ClearTripOnMap();
         };
     }
 }
Exemplo n.º 2
0
        public Task PlaySoundAsync(string filename)
        {
            var tcs = new TaskCompletionSource <bool>();

            // Any existing sound playing?
            if (_player != null)
            {
                //Stop and dispose of any sound
                _player.Stop();
                _player = null;
            }

            string path = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(filename),
                                                              Path.GetExtension(filename));

            var url = NSUrl.FromString(path);

            _player = AVAudioPlayer.FromUrl(url);

            _player.PrepareToPlay();

            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) => {
                _player = null;
                tcs.SetResult(true);
            };

            _player.Play();

            return(tcs.Task);
        }
        void AskQuestionMethod(string question)
        {
            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                _error = new UIAlertView(question, "Please, answer after the signal", null, "NO", "Yes");
                _error.Clicked += (sender, buttonArgs) =>
                {
                    StopListening();
                    _recognitionTask.TrySetResult(buttonArgs.ButtonIndex != _error.CancelButtonIndex);
                };
                _error.Show();
            });

            TextToSpeechService.Speak(question, false).Wait();

            TextToSpeechService.Speak("Please, answer after the signal", false).Wait();

            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                AVAudioSession.SharedInstance().SetCategory(AVAudioSessionCategory.Playback);
                AVAudioSession.SharedInstance().SetActive(true);
                //SystemSound notificationSound = SystemSound.FromFile(@"/System/Library/Audio/UISounds/jbl_begin.caf");
                //notificationSound.AddSystemSoundCompletion(SystemSound.Vibrate.PlaySystemSound);
                //notificationSound.PlaySystemSound();

                _audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(Path.Combine("Sounds", "tap.aif")));
                _audioPlayer.PrepareToPlay();
                _audioPlayer.Play();
            });
             
            Question = question;
            StartListening();
        }
Exemplo n.º 4
0
        public override void ViewWillLayoutSubviews()
        {
            base.ViewWillLayoutSubviews();

            NSError error = new NSError();
            string  backgroundMusicURL = NSBundle.MainBundle.PathForResource("background-music-aac", "caf");

            background_music_player               = AVAudioPlayer.FromUrl(new NSUrl(backgroundMusicURL), out error);
            background_music_player.Volume        = 0.2f;
            background_music_player.NumberOfLoops = -1;
            background_music_player.PrepareToPlay();
            background_music_player.Play();

            // Configure the view.
            var skView = (SKView)View;

            // Create and configure the scene.
            var scene = new MyScene(skView.Bounds.Size);

            scene.ScaleMode = SKSceneScaleMode.AspectFill;

            new UIAlertView("How to play!", "Use swipe gestures to play:\n→ Turn rigth\n← Turn left\n↑ Go up\n↓ Go down\n Easy, right? ;) Enjoy it!", null, "Let's Play!!", null).Show();

            // Present the scene
            skView.PresentScene(scene);
        }
Exemplo n.º 5
0
        public void Play(byte[] data)
        {
            AVAudioPlayer player = AVAudioPlayer.FromData(NSData.FromArray(data));

            player.PrepareToPlay();
            player.Play();
        }
Exemplo n.º 6
0
        private async Task StartPlayerAsync(string title)
        {
            await Task.Run(() => {
                if (player == null)
                {
                    var url = NSUrl.FromFilename($"{title}.mp3");

                    NSError _err = null;

                    player = new AVAudioPlayer(
                        url,
                        AVFileType.MpegLayer3,
                        out _err
                        );

                    player.NumberOfLoops = -1;
                    //player.Looping = true;
                    player.PrepareToPlay();
                    player.Play();
                }
                else
                {
                    if (player.Playing == true)
                    {
                        player.Stop();
                    }
                    else
                    {
                        player.Play();
                    }
                }
            });
        }
Exemplo n.º 7
0
        public void StartPlayEffect(string title)
        {
            try
            {
                if (effect != null)
                {
                    effect.Stop();
                    effect.Dispose();
                    effect = null;
                }
                var url = NSUrl.FromFilename(title + ".mp3");

                NSError _err = null;

                effect = new AVAudioPlayer(
                    url,
                    AVFileType.MpegLayer3,
                    out _err
                    );

                effect.NumberOfLoops = 0;
                effect.PrepareToPlay();
                effect.Play();
            }
            catch
            {
                //ignore
            }
        }
Exemplo n.º 8
0
		private void loadIos(String url)
		{
			_url = url;

			var mediaFile = NSUrl.FromFilename(_url);
			_player = AVAudioPlayer.FromUrl(mediaFile);

			if (null != _player)
			{
			    if (_players.Count == NumberOfPlayers) 
				{
				    _players.Dequeue().Dispose();
				}
				
				_players.Enqueue(_player);

				_player.PrepareToPlay();

				_channel = new SoundChannel();
				_channel.Player = _player;

				_player.DecoderError += delegate {
					this.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
				};

				_player.FinishedPlaying += delegate { 
					_channel.dispatchEvent (new Event (Event.SOUND_COMPLETE));
					//_player.Dispose(); 
				};

				this.dispatchEvent(new Event(Event.COMPLETE));

			}

		}
Exemplo n.º 9
0
        public void Speak(string text, string lang)
        {
            HttpWebRequest  request;
            HttpWebResponse response = null;

            try {
                string uri = String.Format(
                    "http://api.microsofttranslator.com/v2/Http.svc/Speak?appId={0}&text={1}&language={2}",
                    BING_API_ID,
                    text,
                    lang
                    );

                request  = (HttpWebRequest)WebRequest.Create(uri);
                response = (HttpWebResponse)request.GetResponse();

                Stream s = response.GetResponseStream();
                NSData d = NSData.FromStream(s);

                audioPlayer = AVAudioPlayer.FromData(d);
                audioPlayer.PrepareToPlay();
                audioPlayer.Play();
            } catch (System.Net.WebException) {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Exemplo n.º 10
0
        async Task <bool> AskQuestionMethodAsync(string question)
        {
            bool result = false;


            await TextToSpeechService.SpeakAsync(question, false).ConfigureAwait(false);

            await TextToSpeechService.SpeakAsync("Please, answer after the signal", false).ConfigureAwait(false);

            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                AVAudioSession.SharedInstance().SetCategory(AVAudioSessionCategory.Playback);
                AVAudioSession.SharedInstance().SetActive(true);

                _audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(Path.Combine("Sounds", "tap.aif")));
                _audioPlayer.PrepareToPlay();
                _audioPlayer.Play();
            });
            StartListening();
            var intRes = Task.WaitAny(new[] { _voiceRecognitionTCS.Task }, TimeSpan.FromSeconds(10));

            if (intRes == -1)
            {
                throw new TaskCanceledException();
            }
            result = await _voiceRecognitionTCS.Task;

            return(result);
        }
Exemplo n.º 11
0
        public async Task <bool> PlayFile(NSUrl url = null)
        {
            try
            {
                Dispose();

                Player = new AVAudioPlayer(url, "wav", out var err)
                {
                    Volume = 1.0F
                };
                if (err?.Description.HasValue() == true)
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }

            Player.FinishedPlaying += Player_FinishedPlaying;
            Player.DecoderError    += Player_DecoderError;

            if (Player.PrepareToPlay())
            {
                Audio.ConfigureAudio(AVAudioSessionCategory.Playback);
                var result = Player.Play();
                return(await Ended.Task);
            }
            else
            {
                throw new Exception("Failed to play " + url);
            }
        }
        public string GenerateSound()
        {
            String  fileName = "find.mp3";
            NSError error    = null;

            AVAudioSession.SharedInstance().SetCategory(AVAudioSession.CategoryPlayback, out error);

            NSUrl url = new NSUrl("Sounds/" + fileName);

            backgroundmusic        = AVAudioPlayer.FromUrl(url);
            backgroundmusic.Volume = 1.0f;

            backgroundmusic.PrepareToPlay();
            backgroundmusic.BeginInterruption += (object sender, EventArgs e) =>
            {
                backgroundmusic.Play();
                Device.StartTimer(TimeSpan.FromSeconds(1), OnTimerTick);
            };
            backgroundmusic.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
            {
                backgroundmusic = null;
            };
            backgroundmusic.NumberOfLoops = -1;
            backgroundmusic.Play();

            return("iOS sound got called!");
        }
Exemplo n.º 13
0
        public Metronome(float volume, ref BPMModel model)
        {
            SetModel(ref model);

            var soundFile  = new NSUrl($"Sounds/DefaultClick/sound.wav");
            var accentFile = new NSUrl($"Sounds/DefaultClick/accent.wav");

            NSError error;

            _soundPlayer        = new AVAudioPlayer(soundFile, "sound", out error);
            _soundPlayer.Volume = volume;
            _soundPlayer.Pan    = -1;
            _soundPlayer.PrepareToPlay();
            _accentPlayer        = new AVAudioPlayer(accentFile, "sound", out error);
            _accentPlayer.Volume = volume;
            _accentPlayer.Pan    = -1;
            _accentPlayer.PrepareToPlay();
            // TODO: Check error

#if DEBUG
            _testTimer.Elapsed += (object sender, ElapsedEventArgs e) =>
            {
                Debug.WriteLine($"One minute passed, BPM count: {_testMinuteCount}");
                if (_testMinuteCount != _model.CurrentBPM)
                {
                    throw new Exception($"BPM Counts don't match: Current = {_model.CurrentBPM}, Actual = {_testMinuteCount}");
                }
                _testMinuteCount = 0;
            };
#endif
        }
Exemplo n.º 14
0
        private void loadIos(String url)
        {
            _url = url;

            var mediaFile = NSUrl.FromFilename(_url);

            _player = AVAudioPlayer.FromUrl(mediaFile);

            if (null != _player)
            {
                if (_players.Count == NumberOfPlayers)
                {
                    _players.Dequeue().Dispose();
                }

                _players.Enqueue(_player);

                _player.PrepareToPlay();

                _channel        = new SoundChannel();
                _channel.Player = _player;

                _player.DecoderError += delegate {
                    this.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
                };

                _player.FinishedPlaying += delegate {
                    _channel.dispatchEvent(new Event(Event.SOUND_COMPLETE));
                    //_player.Dispose();
                };

                this.dispatchEvent(new Event(Event.COMPLETE));
            }
        }
Exemplo n.º 15
0
        public void Play(string sound, int repeat = 0)
        {
            NSUrl assets = NSUrl.FromString(sound);

            player = AVAudioPlayer.FromUrl(assets);

            player.NumberOfLoops = repeat;
            player.PrepareToPlay();
            player.Play();
        }
        public override bool Prepare()
        {
            if (player == null)
            {
                return(false);
            }

            player.PrepareToPlay();
            return(true);
        }
Exemplo n.º 17
0
        bool PreparePlayer()
        {
            if (player != null)
            {
                player.FinishedPlaying += OnPlaybackEnded;
                player.PrepareToPlay();
            }

            return((player == null) ? false : true);
        }
Exemplo n.º 18
0
        public IOSAVAudioPlayer(Model.PlayableTrackInfo track, System.IO.Stream stream)
        {
            NSError error;

            player = AVAudioPlayer.FromData(NSData.FromStream(stream), out error);

            //TODO: Do something useful here or remove (beware nullptr after playback done).
            player.FinishedPlaying += delegate {};
            player.PrepareToPlay();
        }
        private void SetupAudioPlayer()
        {
            var audioFilePath = NSBundle.MainBundle.PathForResource("mozart", "mp3");
            var audioFileUrl  = new NSUrl(audioFilePath);

            _audioPlayer = new AVAudioPlayer(audioFileUrl, "mozart", out _);
            _audioPlayer.NumberOfLoops = -1;
            _audioPlayer.Volume        = 1;
            _audioPlayer.PrepareToPlay();
        }
Exemplo n.º 20
0
 public void PlaySound()
 {
     try
     {
         _audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename("notification.caf"));
         _audioPlayer.PrepareToPlay();
         _audioPlayer.Play();
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 21
0
    void OnClickPlay(object sender, EventArgs e)
    {
        // MessageBox.Show ("Playing");
        string mediaPath;

        mediaPath = "../../media/applause_y.wav";
        NSUrl         mediaURL      = new NSUrl(mediaPath);
        NSError       error         = new NSError();
        AVAudioPlayer myAudioPlayer = new AVAudioPlayer(mediaURL, error);

        myAudioPlayer.PrepareToPlay();
        myAudioPlayer.Play();
    }
Exemplo n.º 22
0
        public static void PlayAudio()
        {
            var bundle     = NSBundle.MainBundle.PathForResource("3", "wav");
            var alertSound = new NSUrl(bundle);

            AVAudioSession.SharedInstance().SetCategory(AVAudioSessionCategory.Playback, AVAudioSessionCategoryOptions.MixWithOthers);
            AVAudioSession.SharedInstance().SetActive(true);
            audioPlayer.NumberOfLoops = -1;
            audioPlayer.Volume        = 0.01f;
            audioPlayer.PrepareToPlay();
            audioPlayer.Play();
            Console.WriteLine("Playing music");
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            View.BackgroundColor = UIColor.White;
            View.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;

            // iOS is forgiving on audio files. It will handle all three of these just fine.
            string mediaType = "caf"; //"mp3"; //"wav";
            var fileUrl = new NSUrl(NSBundle.MainBundle.PathForResource("Sounds/wubwub", mediaType), false);
            player = AVAudioPlayer.FromUrl(fileUrl);
            player.PrepareToPlay();

            button1 = new UIButton(UIButtonType.RoundedRect);
            button1.SetTitle("Make Some Noise", UIControlState.Normal);
            button1.SizeToFit();
            button1.Center = new CGPoint(View.Bounds.Width / 2f, View.Bounds.Height / 2f);
            button1.TouchUpInside += (sender, e) => {
                player.Play();
            };
            // You can tie in to the event when the sound finishes as well. Here, we just spin the button afterward.
            player.FinishedPlaying += (sender, e) => {
                // (Courtesy of http://www.patridgedev.com/2012/10/05/creating-an-animated-spinner-in-a-monotouch-uiimageview/)
                CABasicAnimation rotationAnimation = CABasicAnimation.FromKeyPath("transform.rotation");
                rotationAnimation.To = NSNumber.FromDouble(Math.PI * 2);
                rotationAnimation.RemovedOnCompletion = true;
                // Give the added animation a key for referencing it later (to remove, in this case).
                button1.Layer.AddAnimation(rotationAnimation, "rotationAnimation");
            };
            Add(button1);

            rand = new Random();
            var variousPlayers = (new[] {
                "Sounds/ding-dong",
                "Sounds/pew-beep",
                "Sounds/wee-ooo",
                "Sounds/wubwub",
            }).Select(path => {
                var url = new NSUrl(NSBundle.MainBundle.PathForResource(path, "wav"), false);
                var audioPlayer = AVAudioPlayer.FromUrl(url);
                audioPlayer.PrepareToPlay();
                return audioPlayer;
            }).ToList();
            button2 = new UIButton(UIButtonType.RoundedRect);
            button2.SetTitle("Random", UIControlState.Normal);
            button2.SizeToFit();
            button2.Center = CGPoint.Add(new CGPoint(View.Bounds.Width / 2f, View.Bounds.Height / 2f), new CGSize(0f, button1.Frame.Height + 8f));
            button2.TouchUpInside += (sender, e) => {
                variousPlayers[rand.Next(variousPlayers.Count - 1)].Play();
            };
            Add(button2);
        }
Exemplo n.º 24
0
        internal override void LoadMusic(SoundMusic music)
        {
            if (audioPlayer != null)
            {
                throw new AudioSystemInternalException("Tried to create a new AudioPlayer but the current instance was not freed.");
            }

            CurrentMusic = music;

            currentMusicDataTypeIsUnsupported = false;

            NSError loadError;

            // TODO: Avoid allocating twice the music size (i.e. by using NSData.FromBytesNoCopy on CurrentMusic.Stream.GetBuffer())
            CurrentMusic.Stream.Position = 0;
            audioPlayer = AVAudioPlayer.FromData(NSData.FromStream(CurrentMusic.Stream), out loadError);

            if (loadError != null)
            {
                if (loadError.Code == (int)AudioFileError.UnsupportedFileType || loadError.Code == (int)AudioFileError.UnsupportedDataFormat)
                {
                    currentMusicDataTypeIsUnsupported = true;
                    musicMediaEvents.Enqueue(new SoundMusicEventNotification(SoundMusicEvent.MetaDataLoaded, null));
                    return;
                }
                throw new AudioSystemInternalException("Music loading failed and failure was not handled. [Error=" + loadError.LocalizedDescription + "].");
            }

            if (audioPlayer == null) // both audioPlayer and loadError are null (happened before when url was not correct)
            {
                throw new AudioSystemInternalException("Music loading failed and failure was not handled. [Unspecified Error].");
            }

            audioPlayer.DecoderError    += OnAudioPlayerDecoderError;
            audioPlayer.FinishedPlaying += OnAudioPlayerFinishedPlaying;

            if (!audioPlayer.PrepareToPlay())
            {
                // this happens sometimes when we put the application on background when starting to play.
                var currentMusicName = CurrentMusic.Name;
                CurrentMusic.SetStateToStopped();
                ResetMusicPlayer();

                Logger.Warning("The music '{0}' failed to prepare to play.", currentMusicName);
            }
            else
            {
                musicMediaEvents.Enqueue(new SoundMusicEventNotification(SoundMusicEvent.MetaDataLoaded, null));
                musicMediaEvents.Enqueue(new SoundMusicEventNotification(SoundMusicEvent.ReadyToBePlayed, null));
            }
        }
Exemplo n.º 25
0
        public void Play(string sound, int repeat = 0)
        {
            var session = AVAudioSession.SharedInstance();

            session.SetCategory(AVAudioSession.CategoryPlayback, out error);

            NSUrl assets = NSUrl.FromString(sound);

            player = AVAudioPlayer.FromUrl(assets);

            player.NumberOfLoops = repeat;
            player.PrepareToPlay();
            player.Play();
        }
Exemplo n.º 26
0
        //static SoundPlayer current;
        //public static SoundPlayer Current
        //{
        //    get
        //    {
        //        if (current == null)
        //        {
        //            current = new SoundPlayer();
        //        }
        //        return current;
        //    }
        //}

        public ISoundPlayer Play(SoundData data, int delay = 500)
        {
            NSError error = null;

            try {
                var audioPlayerData = new NSData(data.Data, NSDataBase64DecodingOptions.None);
                var player          = new AVAudioPlayer(audioPlayerData, "AVFileTypeMPEGLayer3", out error);
                player.PrepareToPlay();
                player.Play();
                Sleep(delay);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message + " " + error?.Description);
            }
            return(this);
        }
Exemplo n.º 27
0
 public void StartAudioPlayback(string AudioFilePath)
 {
     NSError error = null;
       NSUrl audioFileUrl = NSUrl.FromFilename(AudioFilePath);
       _player = AVAudioPlayer.FromUrl(audioFileUrl, out error);
       if (_player != null)
       {
     _player.PrepareToPlay();
     _player.Play();
       }
       else
       {
     throw new Exception("Could not load Accelerometer sensor");
       }
 }
Exemplo n.º 28
0
        public void Play()
        {
            try
            {
                InitMediaPlayer();

                Player.PrepareToPlay();
                mStatus = PlayStatus.Buffering;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message.ToString());

                mStatus = PlayStatus.Error;
                DestroyMediaPlayer();
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Plaies the action.
        /// </summary>
        /// <param name="item">Item.</param>
        /// <param name="args">Arguments.</param>
        private void PlayAction(object item, EventArgs args)
        {
            m_oldSessionCategory = AVAudioSession.SharedInstance().Category;
            AVAudioSession.SharedInstance().SetCategory(AVAudioSessionCategory.Playback);

            //
            m_audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(m_recordingFilePath));
            m_audioPlayer.WeakDelegate    = this;
            m_audioPlayer.MeteringEnabled = true;
            m_audioPlayer.PrepareToPlay();
            m_audioPlayer.Play();

            //UI Update
            {
                this.SetToolbarItems(new UIBarButtonItem[] { m_pauseButton, m_flexItem1, m_recordButton, m_flexItem2, m_trashButton }, true);

                this.ShowNavigationButton(false);

                m_recordButton.Enabled = false;
                m_trashButton.Enabled  = false;
            }

            //Start regular update
            {
                m_playerSlider.Value       = (float)m_audioPlayer.CurrentTime;
                m_playerSlider.MaxValue    = (float)m_audioPlayer.Duration;
                m_viewPlayerDuration.Frame = this.NavigationController.NavigationBar.Bounds;

                m_labelCurrentTime.Text   = NSStringExtensions.TimeStringForTimeInterval(m_audioPlayer.CurrentTime);
                m_labelRemainingTime.Text = NSStringExtensions.TimeStringForTimeInterval((m_ShouldShowRemainingTime) ? (m_audioPlayer.Duration - m_audioPlayer.CurrentTime): m_audioPlayer.Duration);

                m_viewPlayerDuration.SetNeedsLayout();
                m_viewPlayerDuration.LayoutIfNeeded();

                this.NavigationItem.TitleView = m_viewPlayerDuration;

                if (mplayProgressDisplayLink != null)
                {
                    mplayProgressDisplayLink.Invalidate();
                }

                mplayProgressDisplayLink = CADisplayLink.Create(UpdatePlayProgress);
                mplayProgressDisplayLink.AddToRunLoop(NSRunLoop.Current, NSRunLoopMode.Common);
            }
        }
Exemplo n.º 30
0
		public void PlayAudioFile(string fileName)
		{
			NSError error = null;
			AVAudioSession.SharedInstance().SetCategory(AVAudioSession.CategoryPlayback, out error);

			string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
			var url = NSUrl.FromString(sFilePath);
			_player = AVAudioPlayer.FromUrl(url);
			_player.Delegate = this;
			_player.Volume = 100f;
			_player.PrepareToPlay();
			_player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
			{
				_player = null;
			};

			_player.Play();
		}
Exemplo n.º 31
0
        public void PlayAudioFile(string fileName)
        {
            NSError error = null;

            AVAudioSession.SharedInstance().SetCategory(AVAudioSession.CategoryPlayback, out error);

            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
            var    url       = NSUrl.FromString(sFilePath);

            _player          = AVAudioPlayer.FromUrl(url);
            _player.Delegate = this;
            _player.Volume   = 100f;
            _player.PrepareToPlay();
            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) => {
                _player = null;
            };
            _player.Play();
        }
Exemplo n.º 32
0
        public void PlayMusic(string filename)
        {
            StopMusic();

            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(filename), Path.GetExtension(filename));
            var    url       = NSUrl.FromString(sFilePath);

            backgroundMusic = AVAudioPlayer.FromUrl(url);

            backgroundMusic.Volume        = 0.4f;
            backgroundMusic.NumberOfLoops = -1;
            backgroundMusic.PrepareToPlay();
            backgroundMusic.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
            {
                backgroundMusic = null;
            };
            backgroundMusic.Play();
        }
        public bool Load(string filename)
        {
            Unload();

            string path = filename;

            NSError error = null;

            using (NSUrl url = NSUrl.FromFilename(path))
            {
                player = AVAudioPlayer.FromUrl(url, out error);
                player.PrepareToPlay();
                updateVolume();
                //player.MeteringEnabled = true;
            }

            return(error == null);
        }
        void InitializeComponents()
        {
            rectLayer = new CAShapeLayer();

            lblCue = new UILabel(new CGRect(20, 386, 280, 47));
            lblCue.BackgroundColor = UIColor.Clear;
            lblCue.Lines           = 0;
            lblCue.LineBreakMode   = UILineBreakMode.WordWrap;
            lblCue.TextAlignment   = UITextAlignment.Center;
            lblCue.TextColor       = UIColor.White;

            imgRedLaser       = new UIImageView(new CGRect(265, View.Frame.Height - 94, 50, 50));
            imgRedLaser.Image = UIImage.FromFile("powered_by_redlaser.png");

            btnCancel = new UIBarButtonItem("Cancel", UIBarButtonItemStyle.Plain, CancelButtonTapped);
            btnFront  = new UIBarButtonItem("Front", UIBarButtonItemStyle.Plain, FrontButtonTapped);
            btnLight  = new UIBarButtonItem("Light", UIBarButtonItemStyle.Plain, LightButtonTapped);

            toolBar       = new UIToolbar(new CGRect(0, View.Frame.Height - 44, View.Frame.Width, 44));
            toolBar.Items = new [] { btnCancel,
                                     new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                                     btnFront,
                                     new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                                     btnLight };

            View.Layer.AddSublayer(rectLayer);
            View.AddSubviews(new UIView[] { lblCue, imgRedLaser, toolBar });

            NSError error        = new NSError();
            string  beepSoundUrl = NSBundle.MainBundle.PathForResource("beep", "wav");

            beepSound = AVAudioPlayer.FromUrl(new NSUrl(beepSoundUrl), out error);

            if (error == null)
            {
                beepSound.Volume        = 1;
                beepSound.NumberOfLoops = 0;
                beepSound.PrepareToPlay();
            }
            else
            {
                beepSound = null;
            }
        }
Exemplo n.º 35
0
        public Sound(string url, float volume, bool looping)
        {
            var mediaFile = NSUrl.FromFilename(url);
            _audioPlayer =  AVAudioPlayer.FromUrl(mediaFile);
            _audioPlayer.Volume = volume;
            if ( looping )
            {
                _audioPlayer.NumberOfLoops = -1;
            }
            else
            {
                _audioPlayer.NumberOfLoops = 0;
            }

            if (!_audioPlayer.PrepareToPlay())
            {
                Console.WriteLine("Unable to Prepare sound for playback!" + url);
            }
        }
Exemplo n.º 36
0
 public override void Play(string filename)
 {
     try
     {
         /// todo: Устранить загадочную ошибку
         var Soundurl = NSUrl.FromFilename(filename);
         if (player != null)
             player.Stop();
         player = AVAudioPlayer.FromUrl(Soundurl);
         player.Stop();
         player.CurrentTime = player.Duration * 2;
         player.NumberOfLoops = 1;
         player.Volume = 1.0f;
         player.FinishedPlaying += DidFinishPlaying;
         player.PrepareToPlay();
         player.Play();
     }
     catch (Exception e)
     {
         Console.WriteLine("PlaySound: Error: " + e.Message, true);
     }
 }
Exemplo n.º 37
0
        public void PlayAudio(byte[] audioRecording, string fileExtension)
        {
            if (_player != null)
            {
                _player.Dispose();
                _player = null;
            }
            var session = AVAudioSession.SharedInstance();
            if (session == null || audioRecording == null)
            {
                var alert = new UIAlertView("Playback error", "Unable to playback stream", null, "Cancel");
                alert.Show();
                alert.Clicked += (object senderObj, UIButtonEventArgs arg) => alert.DismissWithClickedButtonIndex(0, true);
            }
            else
            {
                NSError error;
                ObjCRuntime.Class.ThrowOnInitFailure = false;
                session.SetCategory(AVAudioSessionCategory.Playback);
                session.SetActive(true, out error);
                var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var temp = Path.Combine(documents, "..", "tmp");
                _tempAudioFile = Path.Combine(temp, Guid.NewGuid() + fileExtension);
                File.WriteAllBytes(_tempAudioFile, audioRecording);
                using (var url = new NSUrl(_tempAudioFile))
                {
                    _player = AVAudioPlayer.FromUrl(url, out error);
                }

                _player.Volume = 1.0f;
                _player.NumberOfLoops = 0;
                _player.FinishedPlaying += player_FinishedPlaying;
                _player.PrepareToPlay();
                _player.Play();
            }
        }
Exemplo n.º 38
0
 void CreateNewPlayer(NSUrl fileURL)
 {
     this.player = AVAudioPlayer.FromUrl (fileURL);
     if (this.player != null) {
         StringBuilder tmp = new StringBuilder ();
         tmp.AppendFormat ("{0} ({1} ch.)", new System.IO.FileInfo (this.player.Url.RelativePath).Name, player.NumberOfChannels);
         fileName.Text = tmp.ToString ();
         this.updateViewForPlayerInfo (this.player);
         this.updateViewForPlayerState (this.player);
         player.NumberOfLoops = 1;
         player.WeakDelegate = this;
         player.PrepareToPlay ();
     }
 }
        /// <summary>
        /// Plaies the action.
        /// </summary>
        /// <param name="item">Item.</param>
        /// <param name="args">Arguments.</param>
        private void PlayAction(object item, EventArgs args)
        {
            m_oldSessionCategory = AVAudioSession.SharedInstance().Category;
            AVAudioSession.SharedInstance ().SetCategory (AVAudioSessionCategory.Playback);

            //
            m_audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(m_recordingFilePath));
            m_audioPlayer.WeakDelegate = this;
            m_audioPlayer.MeteringEnabled = true;
            m_audioPlayer.PrepareToPlay();
            m_audioPlayer.Play();

             //UI Update
             {
                this.SetToolbarItems (new UIBarButtonItem[]{ m_pauseButton,m_flexItem1, m_recordButton,m_flexItem2, m_trashButton}, true);

                this.ShowNavigationButton (false);

                 m_recordButton.Enabled = false;
                 m_trashButton.Enabled = false;
             }

             //Start regular update
             {
                m_playerSlider.Value = (float)m_audioPlayer.CurrentTime;
                m_playerSlider.MaxValue = (float)m_audioPlayer.Duration;
                 m_viewPlayerDuration.Frame = this.NavigationController.NavigationBar.Bounds;

                m_labelCurrentTime.Text = NSStringExtensions.TimeStringForTimeInterval (m_audioPlayer.CurrentTime);
                m_labelRemainingTime.Text = NSStringExtensions.TimeStringForTimeInterval((m_ShouldShowRemainingTime) ? (m_audioPlayer.Duration - m_audioPlayer.CurrentTime): m_audioPlayer.Duration);

                m_viewPlayerDuration.SetNeedsLayout();
                m_viewPlayerDuration.LayoutIfNeeded();

                this.NavigationItem.TitleView = m_viewPlayerDuration;

                if (mplayProgressDisplayLink != null)
                    mplayProgressDisplayLink.Invalidate ();

                mplayProgressDisplayLink = CADisplayLink.Create (UpdatePlayProgress);
                mplayProgressDisplayLink.AddToRunLoop (NSRunLoop.Current, NSRunLoopMode.Common);

             }
        }
Exemplo n.º 40
0
        public Sound(byte[] audiodata, float volume, bool looping)
        {
            var data = NSData.FromArray(audiodata);
            _audioPlayer = AVAudioPlayer.FromData(data);
            _audioPlayer.Volume = volume;
            if ( looping )
            {
                _audioPlayer.NumberOfLoops = -1;
            }
            else
            {
                _audioPlayer.NumberOfLoops = 0;
            }

            if (!_audioPlayer.PrepareToPlay())
            {
                Console.WriteLine("Unable to Prepare sound for playback!");
            }
        }
		public void PlayAudio()
		{
			try {
				var error  = new NSError();
				if (player != null) {
					
				}
				player = AVAudioPlayer.FromUrl (url);
				player.NumberOfLoops = 1;
				player.Volume = 1.0f;
				player.FinishedPlaying += DidFinishPlaying;
				player.PrepareToPlay ();
				player.Play ();
			} 
			catch (Exception ex) 
			{
				var tt = ex.Message;
			}
		}
		void InitializeComponents () 
		{
			rectLayer = new CAShapeLayer ();

			lblCue = new UILabel (new CGRect (20, 386, 280, 47));
			lblCue.BackgroundColor = UIColor.Clear;
			lblCue.Lines = 0;
			lblCue.LineBreakMode = UILineBreakMode.WordWrap;
			lblCue.TextAlignment = UITextAlignment.Center;
			lblCue.TextColor = UIColor.White;

			imgRedLaser = new UIImageView (new CGRect (265, View.Frame.Height - 94, 50, 50));
			imgRedLaser.Image = UIImage.FromFile ("powered_by_redlaser.png");

			btnCancel = new UIBarButtonItem ("Cancel", UIBarButtonItemStyle.Plain, CancelButtonTapped);
			btnFront = new UIBarButtonItem ("Front", UIBarButtonItemStyle.Plain, FrontButtonTapped);
			btnLight = new UIBarButtonItem ("Light", UIBarButtonItemStyle.Plain, LightButtonTapped);

			toolBar = new UIToolbar (new CGRect(0, View.Frame.Height - 44, View.Frame.Width, 44));
			toolBar.Items = new [] { btnCancel,
				new UIBarButtonItem (UIBarButtonSystemItem.FlexibleSpace),
				btnFront,
				new UIBarButtonItem (UIBarButtonSystemItem.FlexibleSpace),
				btnLight
			};

			View.Layer.AddSublayer (rectLayer);
			View.AddSubviews (new UIView[] { lblCue, imgRedLaser, toolBar });

			NSError error = new NSError ();
			string beepSoundUrl = NSBundle.MainBundle.PathForResource ("beep", "wav");
			beepSound = AVAudioPlayer.FromUrl (new NSUrl (beepSoundUrl), out error);

			if (error == null) {
				beepSound.Volume = 1;
				beepSound.NumberOfLoops = 0;
				beepSound.PrepareToPlay ();
			} else {
				beepSound = null;
			}
		}
Exemplo n.º 43
0
 Util()
 {
     _audioPlayer = AVAudioPlayer.FromUrl (NSUrl.FromFilename ("sounds/sound.m4v"));
     _audioPlayer.PrepareToPlay ();
 }
        private void playerPlayButtonTouchUpInside_Event(object sender, EventArgs e)
        {
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
            var fileName = Path.Combine (documents, fileNameLabel.Text);

            _audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(fileName));
            if (_audioPlayer != null) {
                _audioPlayer.FinishedPlaying += audioPlayerFinishedPlaying_Event;
                _audioPlayer.PrepareToPlay ();
                _audioPlayer.Play ();

                progressBar.MinValue = 0.0f;
                progressBar.Value = 0.0f;
                progressBar.MaxValue = (float)_audioPlayer.Duration;

                updateTimer = NSTimer.CreateRepeatingScheduledTimer (TimeSpan.FromSeconds (0.01), delegate {
                    progressBar.Value = (float) _audioPlayer.CurrentTime;
                });

                playerPlayButton.Selected = true;
            }
        }
Exemplo n.º 45
0
        private void LoadNewMusic(SoundMusic lastPlayRequestMusicInstance)
        {
            if(audioPlayer != null)
                throw new AudioSystemInternalException("Tried to create a new AudioPlayer but the current instance was not freed.");

            currentMusic = lastPlayRequestMusicInstance;

            currentMusicDataTypeIsUnsupported = false;

            NSError loadError;

            // TODO: Avoid allocating twice the music size (i.e. by using NSData.FromBytesNoCopy on currentMusic.Stream.GetBuffer())
            currentMusic.Stream.Position = 0;
            audioPlayer = AVAudioPlayer.FromData(NSData.FromStream(currentMusic.Stream), out loadError);

            if (loadError != null)
            {
                if (loadError.Code == (int) AudioFileError.UnsupportedFileType || loadError.Code == (int) AudioFileError.UnsupportedDataFormat)
                {
                    currentMusicDataTypeIsUnsupported = true;
                    musicMediaEvents.Enqueue(new SoundMusicEventNotification(SoundMusicEvent.MetaDataLoaded, null));
                    return;
                }
                throw new AudioSystemInternalException("Music loading failed and failure was not handled. [Error="+loadError.LocalizedDescription+"].");
            }

            if (audioPlayer == null) // both audioPlayer and loadError are null (happened before when url was not correct) 
                throw new AudioSystemInternalException("Music loading failed and failure was not handled. [Unspecified Error].");

            audioPlayer.DecoderError += OnAudioPlayerDecoderError;
            audioPlayer.FinishedPlaying += OnAudioPlayerFinishedPlaying;

            if (!audioPlayer.PrepareToPlay())
            {
                // this happens sometimes when we put the application on background when starting to play.
                var currentMusicName = currentMusic.Name;
                currentMusic.SetStateToStopped();
                ResetMusicPlayer();

                Logger.Warning("The music '{0}' failed to prepare to play.", currentMusicName);
            }
            else
            {
                musicMediaEvents.Enqueue(new SoundMusicEventNotification(SoundMusicEvent.MetaDataLoaded, null));
                musicMediaEvents.Enqueue(new SoundMusicEventNotification(SoundMusicEvent.ReadyToBePlayed, null));
            }
        }
Exemplo n.º 46
0
        public void Speak (string text, string lang)
        {
            HttpWebRequest request;
            HttpWebResponse response = null;
            
            try {
                string uri = String.Format (
                    "http://api.microsofttranslator.com/v2/Http.svc/Speak?appId={0}&text={1}&language={2}",
                    BING_API_ID,
                    text,
                    lang
                );
                
                request = (HttpWebRequest)WebRequest.Create (uri);
                response = (HttpWebResponse)request.GetResponse ();

                Stream s = response.GetResponseStream ();
                NSData d = NSData.FromStream (s);

                audioPlayer = AVAudioPlayer.FromData (d);
                audioPlayer.PrepareToPlay ();
                audioPlayer.Play ();
                
            } catch (System.Net.WebException) {
                
                if (response != null)
                    response.Close ();
            }
        }