public void DidToggleAudioLoop(ARDMainView mainView)
        {
            if (mainView.IsAudioLoopPlaying)
            {
                _audioPlayer.Stop();
            }
            else
            {
                _audioPlayer.Play();
            }

            mainView.IsAudioLoopPlaying = _audioPlayer.Playing;
        }
예제 #2
0
 public void StartPlayTrack()
 {
     if (isPermissionGranted)
     {
         trackModels  = GetTrackList();
         currentTrack = trackModels[0];
         _mediaPlayer = AVAudioPlayer.FromUrl(new Foundation.NSUrl(currentTrack.Url));
         _mediaPlayer.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
         {
             _mediaPlayer = null;
         };
         _mediaPlayer?.Play();
     }
 }
예제 #3
0
        public void PlayRecording(string path)
        {
            if (_audioPlayer != null)
            {
                _audioPlayer.Stop();
                _audioPlayer.Dispose();
            }

            if (File.Exists(Constants.INITIAL_AUDIO_FILE_PATH))
            {
                _url         = NSUrl.FromFilename(Constants.INITIAL_AUDIO_FILE_PATH);
                _audioPlayer = AVAudioPlayer.FromUrl(_url, out _error);
                _audioPlayer.Play();
                _audioPlayer.FinishedPlaying += PlayCompletion;
            }

            if (File.Exists(path) && !File.Exists(Constants.INITIAL_AUDIO_FILE_PATH))
            {
                try
                {
                    ObjCRuntime.Class.ThrowOnInitFailure = false;
                    _url         = NSUrl.FromString(path);
                    _audioPlayer = AVAudioPlayer.FromUrl(_url);
                    _audioPlayer.Play();
                    _audioPlayer.FinishedPlaying += PlayCompletion;
                }

                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
        }
예제 #4
0
        public void PlaySound(string fileName)
        {
            NSUrl songUrl;

            //Music enabled?
            if (!MusicOn)
            {
                return;
            }
            if (audio != null)
            {
                audio.Stop();
                audio.Dispose();
            }

            songUrl = new NSUrl("Sounds/" + fileName);
            NSError err;

            audio = new AVAudioPlayer(songUrl, "mp3", out err)
            {
                Volume = MusicVolume
            };
            audio.FinishedPlaying += delegate
            {
                audio = null;
            };
            audio.NumberOfLoops = 0;
            audio.Play();
        }
예제 #5
0
        public void PlaySound(string FileName)
        {
            NSUrl         songURl;
            AVAudioPlayer audio = new AVAudioPlayer;

            //music enabled
            if (!MusicOn)
            {
                return;
            }

            //Any existing sound effects
            if (audio != null)
            {
                audio.Stop();
                audio.Dispose();
            }

            //initialze background music
            songURl                = new NSUrl("Sounds/" + FileName);
            audio                  = new AVAudioPlayer(songURl, "mp3");
            audio.Volume           = MusicVolume;
            audio.FinishedPlaying += delegate {
                audio = null;
            };
            audio.NumberOfLoops = 0;
            audio.Play();
        }
예제 #6
0
        public void Play()
        {
            NSUrl songURL;


            // Any existing background music?
            if (backgroundMusic != null)
            {
                //Stop and dispose of any background music
                backgroundMusic.Stop();
                backgroundMusic.Dispose();
            }

            // Initialize background music
            songURL = new NSUrl(filePath);
            NSError err;

            backgroundMusic                  = new AVAudioPlayer(songURL, "wav", out err);
            backgroundMusic.Volume           = MusicVolume;
            backgroundMusic.FinishedPlaying += delegate {
                // backgroundMusic.Dispose();
                backgroundMusic = null;
            };
            backgroundMusic.NumberOfLoops = -1;
            backgroundMusic.Play();
        }
예제 #7
0
        private SoundChannel playIos(double startTime = 0, int loops = 0, SoundTransform sndTransform = null)
        {
            if (null == _player)
            {
                return(null);
            }

            if (loops < 0)
            {
                loops = 0;
            }

            _player.NumberOfLoops = loops;

            if (startTime > 0)
            {
                _player.PlayAtTime(startTime);
            }
            else
            {
                _player.Play();
            }

            return(_channel);
        }
예제 #8
0
        public void PlaySound(int samplingRate, byte[] pcmData)
        {
            int numSamples = pcmData.Length / (bitsPerSample / 8);

            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter writer       = new BinaryWriter(memoryStream, Encoding.ASCII);

            // Construct WAVE header.
            writer.Write(new char[] { 'R', 'I', 'F', 'F' });
            writer.Write(36 + sizeof(short) * numSamples);
            writer.Write(new char[] { 'W', 'A', 'V', 'E' });
            writer.Write(new char[] { 'f', 'm', 't', ' ' });                // format chunk
            writer.Write(16);                                               // PCM chunk size
            writer.Write((short)1);                                         // PCM format flag
            writer.Write((short)numChannels);
            writer.Write(samplingRate);
            writer.Write(samplingRate * numChannels * bitsPerSample / 8);   // byte rate
            writer.Write((short)(numChannels * bitsPerSample / 8));         // block align
            writer.Write((short)bitsPerSample);
            writer.Write(new char[] { 'd', 'a', 't', 'a' });                // data chunk
            writer.Write(numSamples * numChannels * bitsPerSample / 8);

            // Write data as well.
            writer.Write(pcmData, 0, pcmData.Length);

            memoryStream.Seek(0, SeekOrigin.Begin);
            NSData        data        = NSData.FromStream(memoryStream);
            AVAudioPlayer audioPlayer = AVAudioPlayer.FromData(data);

            audioPlayer.Play();
        }
예제 #9
0
파일: DeviceService.cs 프로젝트: uemegu/FNO
        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
            }
        }
 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();
         };
     }
 }
예제 #11
0
        void ControlBackgroundMusic(string controlType, float volumeLevel)
        {
            if (((backgroundMusicPlayer == null) ||
                 (backgroundMusicPlayer.Playing == false)) &&
                (controlType == "Play"))
            {
                backgroundMusicPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(GetRandomBackgroundMusic(backgroundMusicPlayer == null ? string.Empty :
                                                                                                          "./" + backgroundMusicPlayer.Url.RelativePath)));
                backgroundMusicPlayer.NumberOfLoops = -1;
                backgroundMusicPlayer.Volume        = volumeLevel;

                backgroundMusicPlayer.Play();
            }
            else if (backgroundMusicPlayer != null)
            {
                if (controlType == "Stop")
                {
                    backgroundMusicPlayer.Stop();
                }
                else if (controlType == "Pause")
                {
                    backgroundMusicPlayer.Pause();
                }
                else if (controlType == "Resume")
                {
                    backgroundMusicPlayer.Play();
                }
            }
        }
예제 #12
0
        internal void Play()
        {
            if (_sound == null)
            {
                return;
            }

#if IOS
            // AVAudioPlayer sound.Stop() does not reset the playback position as XNA does.
            // Set Play's currentTime to 0 to ensure playback at the start.
            _sound.CurrentTime = 0.0;
#endif
            _sound.Play();

            _playCount++;
        }
예제 #13
0
        public void PlayAudio(string path)
        {
            try
            {
                path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), path); // this line is added to place file in iOS temp directory, may not be required in Halza app
                if (player != null)
                {
                    //Stop and dispose of any background music
                    player.Stop();
                    player.Dispose();
                }

                // Initialize background music
                NSUrl   songURL = new NSUrl("Sounds/" + path);
                NSError err;
                player = new AVAudioPlayer(songURL, "acc", out err);
                player.FinishedPlaying += delegate
                {
                    player = null;
                };
                //player.NumberOfLoops = 0;
                player.Play();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #14
0
 /// <summary>
 /// Sliders the end.
 /// </summary>
 /// <param name="item">Item.</param>
 /// <param name="args">Arguments.</param>
 private void SliderEnd(object item, EventArgs args)
 {
     if (m_wasPlaying)
     {
         m_audioPlayer.Play();
     }
 }
예제 #15
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        private async Task <AVAudioPlayer> NewSound(string filename, float defaultVolume, bool isLooping = false)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            var     songUrl = new NSUrl(Path.Combine(SoundPath, filename));
            NSError err;
            var     fileType = filename.Split('.').Last();
            var     sound    = new AVAudioPlayer(songUrl, fileType, out err)
            {
                Volume        = defaultVolume,
                NumberOfLoops = isLooping ? -1 : 0
            };

            //// this will stop the current playing sound, but will also introduce weird noise....
            //if (_soundPlaying != null && _soundPlaying.Playing)
            //{
            //	_soundPlaying.Stop();
            //	_soundPlaying.Dispose();
            //}

            sound.FinishedPlaying += SoundOnFinishedPlaying;

            sound.Play();

            return(sound);
        }
예제 #16
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);
        }
예제 #17
0
        public static void PlayFile(string FileName)
        {
            var url = NSUrl.FromFilename(FileName);

            _player = AVAudioPlayer.FromUrl(url);
            _player.Play();
        }
예제 #18
0
        public void PlaySound(int samplingRate, byte[] pcmData)
        {
            int numSamples = pcmData.Length / (bitsPerSample / 8);

            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.ASCII);

            binaryWriter.Write(new char[] { 'R', 'I', 'F', 'F' });
            binaryWriter.Write(36 + sizeof(short) * numSamples);
            binaryWriter.Write(new char[] { 'W', 'A', 'V', 'E' });
            binaryWriter.Write(new char[] { 'f', 'm', 't', ' ' });
            binaryWriter.Write(16);
            binaryWriter.Write((short)1);
            binaryWriter.Write((short)numChannels);
            binaryWriter.Write(samplingRate);
            binaryWriter.Write(samplingRate * numChannels * bitsPerSample / 8);
            binaryWriter.Write((short)(numChannels * bitsPerSample / 8));
            binaryWriter.Write((short)bitsPerSample);
            binaryWriter.Write(new char[] { 'd', 'a', 't', 'a' });
            binaryWriter.Write(numSamples * numChannels * bitsPerSample / 8);

            binaryWriter.Write(pcmData, 0, pcmData.Length);

            memoryStream.Seek(0, SeekOrigin.Begin);
            NSData        data        = NSData.FromStream(memoryStream);
            AVAudioPlayer audioPlayer = AVAudioPlayer.FromData(data);

            audioPlayer.Play();
        }
        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();
        }
예제 #20
0
        public async Task <byte[]> TakePhoto()
        {
            var session = AVAudioSession.SharedInstance();

            session.SetCategory(AVAudioSessionCategory.Record, AVAudioSessionCategoryOptions.DuckOthers);
            session.SetActive(true);

            NSError nSError;

            aVPlayer = new AVAudioPlayer(new NSUrl("Sounds/5minsilence.mp3"), "mp3", out nSError);
            aVPlayer.FinishedPlaying += delegate {
                aVPlayer = null;
            };
            aVPlayer.Volume = 10f;

            aVPlayer.Play();

            var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
            var sampleBuffer    = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);

            var jpegImageAsNsData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);
            var jpegAsByteArray   = jpegImageAsNsData.ToArray();

            return(jpegAsByteArray);
        }
예제 #21
0
 public void Play()
 {
     ThreadPool.QueueUserWorkItem(delegate
     {
         _audioPlayer.Play();
     });
 }
        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!");
        }
예제 #23
0
        public void PlayBackgroundMusic(string filename)
        {
            NSUrl songURL;

            // Music enabled?
            if (!MusicOn)
            {
                return;
            }

            // Any existing background music?
            if (backgroundMusic != null)
            {
                //Stop and dispose of any background music
                backgroundMusic.Stop();
                backgroundMusic.Dispose();
            }

            // Initialize background music
            songURL = new NSUrl("Son/" + filename);
            NSError err;

            backgroundMusic                  = new AVAudioPlayer(songURL, "mp3", out err);
            backgroundMusic.Volume           = MusicVolume;
            backgroundMusic.FinishedPlaying += delegate {
                // backgroundMusic.Dispose();
                backgroundMusic = null;
            };
            backgroundMusic.NumberOfLoops = -1;
            backgroundMusic.Play();
            backgroundSong = filename;
        }
예제 #24
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();
                    }
                }
            });
        }
예제 #25
0
        public void PlaySound(string filename)
        {
            NSUrl songURL;

            // Music enabled?
            if (!EffectsOn)
            {
                return;
            }

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

            // Initialize background music
            songURL = new NSUrl("Son/" + filename);
            NSError err;

            soundEffect                  = new AVAudioPlayer(songURL, "mp3", out err);
            soundEffect.Volume           = EffectsVolume;
            soundEffect.FinishedPlaying += delegate {
                soundEffect = null;
            };
            soundEffect.NumberOfLoops = 0;
            soundEffect.Play();
        }
예제 #26
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();
                }
            }
        }
예제 #27
0
        public void PlayAudio(SoundEffectType effect)
        {
            string fileName = "";

            switch (effect)
            {
            case SoundEffectType.FacebookAlert:
                fileName = "facebook_sound.mp3";
                break;

            case SoundEffectType.FacebookPop:
                fileName = "facebook_pop.mp3";
                break;

            case SoundEffectType.Notification:
                fileName = "";
                break;
            }

            var filePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName),

                                                               Path.GetExtension(fileName));

            NSError outError;
            NSUrl   fileURL = new NSUrl(fileName);

            using (AVAudioPlayer audioPlayer = new AVAudioPlayer(url: fileURL, "video/mp4", outError: out outError))
            {
                var url = NSUrl.FromString(filePath);
                audioPlayer.Play();
            }
        }
예제 #28
0
        public void Play(byte[] data)
        {
            AVAudioPlayer player = AVAudioPlayer.FromData(NSData.FromArray(data));

            player.PrepareToPlay();
            player.Play();
        }
        public void PlaySound(Queue <byte[]> audio)
        {
            if (audio == null)
            {
                throw new ApplicationException("audio is null");
            }

            if (audio.Count > 0)
            {
                var audioSource = audio.Dequeue();

                SetAudioSettings();
                var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Audio.wav");

                File.WriteAllBytes(filePath, (byte[])audioSource);

                _player = AVAudioPlayer.FromUrl(NSUrl.FromFilename(filePath));

                if (_player == null)
                {
                    throw new ApplicationException("_player is null");
                }

                _player.FinishedPlaying += (sender, e) =>
                {
                    PlaySound(audio);
                };

                _player.Play();
            }
        }
예제 #30
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);
        }
예제 #31
0
        public AudioPlay(string file)
        {
            player = AVAudioPlayer.FromUrl (new NSUrl (file));
            if (player != null){
                player.NumberOfLoops = -1;

                player.Play ();
            }
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			_imageView = new UIImageView (View.Bounds); //UIButton.FromType(UIButtonType.Custom);
			//_imageView.ContentMode = UIViewContentMode.ScaleAspectFill;
			//_imageView.Frame = View.Bounds;
			//_imageView.ClipsToBounds = true;
			//_imageView.Layer.MasksToBounds = true;
			//_imageView.Center = View.Center;
			var orientation = UIDevice.CurrentDevice.Orientation;
            FlashCardImageCrop crop;
            string xCassetName;
            if (orientation == UIDeviceOrientation.Portrait)
            {
                crop = _flashCard.ImageDef[AspectRatio.Twelve16].Portrait.Crop;
                xCassetName = _flashCard.ImageDef[AspectRatio.Twelve16].Portrait.XCasset;
            } else
            {
                crop = _flashCard.ImageDef[AspectRatio.Twelve16].Landscape.Crop;
                xCassetName = _flashCard.ImageDef[AspectRatio.Twelve16].Landscape.XCasset;
            }
			_imageView.Layer.ContentsRect = new CGRect { X = crop.X1, Y = crop.Y1, Width = crop.Width, Height = crop.Height  };
			_imageView.Image = UIImage.FromBundle (xCassetName);
			//_imageView.SetImage(UIImage.FromBundle(_flashCard.Image), UIControlState.Normal);


			_cancelButton = UIButton.FromType(UIButtonType.Custom);
			_cancelButton.Frame = View.Bounds;
			_cancelButton.TouchUpInside += (object sender, EventArgs e) => {
				if(_eventHandler != null){
					_eventHandler.FlashCardDismissed();
					_itemSound.Stop();
				}

			};

			View.AddSubview (_imageView);
			View.AddSubview (_cancelButton);


			var songURL = new NSUrl ("sounds/" + _flashCard.Sound);
			NSError err;
			_itemSound = new AVAudioPlayer(songURL, AVFileType.MpegLayer3, out err);
			_itemSound.Volume = 7;
			//			_itemSound.FinishedPlaying += delegate { 
			//				// backgroundMusic.Dispose(); 
			//				_itemSound = null;
			//			};
			_itemSound.NumberOfLoops=0;
			_itemSound.Play();
			//backgroundSong=filename;
		}
        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);
        }
예제 #34
0
		public bool Play (IMusicTrack music, bool loop) {
			var avfMusic = (AvfMusicTrack)music;
			if (avfMusic == null)
				throw new ArgumentException ("Music must be an AvfBackgroundMusic object.", "music");
			_music = avfMusic;

			if (_player != null)
				_player.Dispose ();

			_player = AVAudioPlayer.FromUrl (new NSUrl (Assets.ResolvePath (avfMusic.Path)));
			_player.Volume = _volume;
			_player.NumberOfLoops = loop ? -1 : 0;
			return _player.Play ();
		}
예제 #35
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");
       }
 }
예제 #36
0
 private void Play(string fileName)
 {
     if (IsJokeDay)
         try
         {
             if (_player != null)
             {
                 _player.Stop();
                 _player.Dispose();
             }
             NSUrl ulr = NSUrl.FromFilename(fileName);
             _player = AVAudioPlayer.FromUrl(ulr);
             _player.Play();
         }
         catch
         {
         }
 }
예제 #37
0
		void RenderAudioAsync ()
		{
			CFUrl sourceUrl = CFUrl.FromFile (NSBundle.MainBundle.PathForResource ("composeaudio", "mp3"));
			CFUrl destinationUrl = CFUrl.FromFile (System.IO.Path.Combine (System.Environment.GetFolderPath (Environment.SpecialFolder.Personal), "output.caf"));
			
			if (busy)
				return;

			busy = true;
			SetCaption ("Rendering...");
			
			var thread = new System.Threading.Thread (() =>
			{
				try {
					RenderAudio (sourceUrl, destinationUrl);
				} catch (Exception ex) {
					Console.WriteLine (ex);
				}
				BeginInvokeOnMainThread (() =>
				{
					SetCaption ("Playing...");

					using (var playUrl = new NSUrl (destinationUrl.Handle)) {
						player = AVAudioPlayer.FromUrl (playUrl);
					}
					
					player.Play ();
					player.FinishedPlaying += (sender, e) =>
					{
						BeginInvokeOnMainThread (() =>
						{
							player.Dispose ();
							player = null;
							SetCaption ("Render audio");
							busy = false;
						});
					};
				});
			});
			thread.IsBackground = true;
			thread.Start ();
		}
예제 #38
0
        public void PlaySound(WordModel theWord, List<WaveModel> waves)
        {
            if (theWord.Status == WordStatus.COMPLETE)
            {
                int lastPlayedIdx = -1;
                if (mLastPlayed.ContainsKey(theWord.Word))
                    lastPlayedIdx = mLastPlayed[theWord.Word];

                if (lastPlayedIdx < waves.Count - 1)
                    lastPlayedIdx++;
                else
                    lastPlayedIdx = 0;

                var localFile = Path.Combine ("file://", MainModel.GetSoundsDirectory (), waves[lastPlayedIdx].WaveFileName);
                mCurrentSound = AVAudioPlayer.FromData (MonoTouch.Foundation.NSData.FromFile(localFile));
                mCurrentSound.Play ();

                mLastPlayed[theWord.Word] = lastPlayedIdx;
            }
        }
예제 #39
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);
     }
 }
예제 #40
0
파일: Sound.cs 프로젝트: Surfoo/WF.Player
		public void PlaySound(Media media)
		{
			NSError error;

			if (_soundPlayer != null) {
				_soundPlayer.Stop();
				_soundPlayer = null;
			}

			if (media == null || media.Data == null || media.Data.Length == 0)
				return;

			try {
				_soundPlayer = AVAudioPlayer.FromData(NSData.FromArray (media.Data), out error);
			}
			catch (Exception e) {
			}

			if (_soundPlayer != null)
				_soundPlayer.Play ();
//			else
//				throw new InvalidCastException(String.Format ("Audio file format of media {0} is not valid",media.Name));
		}
예제 #41
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();
            }
        }
예제 #42
0
		public void playAudio(string word)
		{
			var newURL = new NSUrl ("Audio_Files/"+word+".m4a");
			var backupURL = new NSUrl ("Audio_Files/oat.m4a");
			session.SetActive (true);

			try
			{
				player = AVAudioPlayer.FromUrl (newURL);
			}
			catch(Exception ex) {

				//just play a random word so it doesn't crash.  Used to determine gaps
				player = AVAudioPlayer.FromUrl (backupURL);
			}
			AVAudioPlayerDelegate avDel = new AVAudioPlayerDelegate ();
			player.Delegate = avDel;

			player.Play ();
		}
예제 #43
0
		public void StartSound(Media media)
		{
			NSError error;
			if (soundPlayer != null) {
				soundPlayer.Stop();
				soundPlayer = null;
			}
			soundPlayer = AVAudioPlayer.FromData(NSData.FromArray (media.Data), out error);
			if (soundPlayer != null)
				soundPlayer.Play ();
			else
				logMessage (LogLevel.Error,String.Format ("Audio file format of media {0} is not valid",media.Name));
		}
예제 #44
0
파일: Bing.cs 프로젝트: GSerjo/Seminars
        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 ();
            }
        }   
예제 #45
0
		public void playAudio()
		{
			session.SetActive (true);

			player = AVAudioPlayer.FromUrl (url);

			AVAudioPlayerDelegate avDel = new AVAudioPlayerDelegate ();
			player.Delegate = avDel;

			player.Play ();
	
		}
예제 #46
0
		public static async Task<bool> LikePost(Post post, UIButton likeButton, UITableView tableView = null, NSIndexPath indexPath = null)
		{
			if (post.liked || post.IsExpired())
			{
				return false;
			}

			likeButton.SetImage(UIImage.FromBundle("LikeSelected"), UIControlState.Normal);
			likeButton.SetImage(UIImage.FromBundle("LikeSelected"), UIControlState.Highlighted);
			likeButton.SetImage(UIImage.FromBundle("LikeSelected"), UIControlState.Selected);
			UIView.Animate(.3, delegate
			{
				likeButton.Transform = CoreGraphics.CGAffineTransform.MakeScale((nfloat)1.7, (nfloat)1.7);
			}, delegate
			{
				likeButton.Transform = CoreGraphics.CGAffineTransform.MakeScale((nfloat)1, (nfloat)1);
			});



			if (post.userPoster.idUser != Globe.SharedInstance.User.idUser)
			{
				post.liked = true;
				post.expiration = post.expiration + 60000;
				likeButton.SetImage(UIImage.FromBundle("LikeSelected"), UIControlState.Normal);
				likeButton.SetImage(UIImage.FromBundle("LikeSelected"), UIControlState.Highlighted);
				likeButton.SetImage(UIImage.FromBundle("LikeSelected"), UIControlState.Selected);


				AVAudioSession audioSession = AVAudioSession.SharedInstance();
				NSError error = audioSession.SetCategory(AVAudioSessionCategory.Ambient, AVAudioSessionCategoryOptions.MixWithOthers);
				audioSession.SetActive(true, out error);


				AVAudioPlayer player = new AVAudioPlayer(new NSUrl("ticksound.m4a"), "m4a", out error);
				player.NumberOfLoops = 1;
				player.Play();
				player.FinishedPlaying += (sender, e) =>
				{
					player.Stop();
					player = null;
				};

				try
				{
					bool result = await TenServices.LikePost(post);
					if (!result)
					{
						post.liked = false;
						likeButton.SetImage(UIImage.FromBundle("Like"), UIControlState.Normal);
						likeButton.SetImage(UIImage.FromBundle("Like"), UIControlState.Highlighted);
						likeButton.SetImage(UIImage.FromBundle("Like"), UIControlState.Selected);
					}
					else {
						if (tableView != null && indexPath != null)
						{
							tableView.ReloadRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.None);
						}
					}
					return result;
				}
				catch (RESTError)
				{
					post.liked = false;
					likeButton.SetImage(UIImage.FromBundle("Like"), UIControlState.Normal);
					likeButton.SetImage(UIImage.FromBundle("Like"), UIControlState.Highlighted);
					likeButton.SetImage(UIImage.FromBundle("Like"), UIControlState.Selected);
				}
				finally
				{
					if (!post.liked)
					{
						post.expiration = post.expiration - 60000;
					}
				}
			}

			return false;
		}
예제 #47
0
 void startPlaybackForPlayer(AVAudioPlayer p)
 {
     if (p.Play ())
     {
         this.updateViewForPlayerState (p);
     }
     else
         Console.WriteLine (@"Could not play {0}", p.Url);
 }
예제 #48
0
        public void PlayAudio(string fileName)
        {
            if (!SettingsHelper.Mute) {
                if (audioPlayer != null && audioPlayer.Playing)
                    audioPlayer.Stop ();
                var filePath = NSUrl.FromFilename (fileName);
                var newPlayer = AVAudioPlayer.FromUrl (filePath);
                newPlayer.PrepareToPlay ();
                audioPlayer = newPlayer;
                audioPlayer.Volume = 1;
                audioPlayer.Play ();

                audioPlayer.FinishedPlaying += (sender, e) => {
                    audioPlayer.Play ();
                };
            }
        }
        /// <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);

             }
        }
예제 #50
0
 public static void PlayFile(string FileName)
 {
     var url = NSUrl.FromFilename(FileName);
     _player = AVAudioPlayer.FromUrl(url);
     _player.Play();
 }
		void playAudio ()
		{
			Debug.WriteLine ("Playing converted audio...");
			
			UpdateFormatInfo (fileInfo, destinationURL);
			startButton.SetTitle ("Playing Output File...", UIControlState.Disabled);

			// set category back to something that will allow us to play audio since kAudioSessionCategory_AudioProcessing will not
			AudioSession.Category = AudioSessionCategory.MediaPlayback;

			// play the result
			NSError error;
			player = AVAudioPlayer.FromUrl (destinationURL, out error);
			if (player == null) {
				Debug.Print ("AVAudioPlayer failed: {0}", error);
				updateUI ();
				return;
			} 

			player.DecoderError += delegate {
				Debug.WriteLine ("DecoderError");
				updateUI ();
			};

			player.BeginInterruption += delegate {
				Debug.WriteLine ("BeginInterruption");
				player.Stop ();
				updateUI ();
			};

			player.FinishedPlaying += delegate(object sender, AVStatusEventArgs e) {
				Debug.WriteLine ("FinishedPlaying");
				updateUI ();
				player = null;
			};

			if (!player.Play ()) {
				Debug.WriteLine ("ERROR: Cannot play the file");
				updateUI ();
				player = null;
			}
		}
 void AudioPlayer.PlayAudio()
 {
     Player= new AVAudioPlayer(NSUrl.FromFilename(Path.Combine(AudioFilePath, AudioFileName + ".wav")),".wav",out Error);
     Player.Play();
 }
        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;
            }
        }
		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;
			}
		}