public static ButtonBeep Create(string name, float volume) { var result = new ButtonBeep(volume); if (ButtonBeep.players.TryGetValue(name, out AVAudioPlayer player)) { result.Player = player; } else { var splitted = name.Split(new char[] { '.' }, System.StringSplitOptions.RemoveEmptyEntries); var url = NSBundle.MainBundle.GetUrlForResource($"Sounds/{splitted[0]}", splitted[1]); if (url == null) { return(null); } player = AVAudioPlayer.FromUrl(url, out NSError error); if (player != null) { player.PrepareToPlay(); result.Player = player; ButtonBeep.players[name] = player; } else { return(null); } } return(result); }
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); } } }
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(); } } }
public OperationResult <double> Initialize(string audioFilePath) { if (string.IsNullOrEmpty(audioFilePath) || !File.Exists(audioFilePath)) { return(OperationResult <double> .AsFailure("Invalid audio file path specified")); } var audioSession = AVAudioSession.SharedInstance(); var error = audioSession.SetCategory(AVAudioSessionCategory.Playback); if (error != null) { return(OperationResult <double> .AsFailure(error.LocalizedDescription)); } error = audioSession.SetActive(true); if (error != null) { return(OperationResult <double> .AsFailure(error.LocalizedDescription)); } NSUrl audioUrl = NSUrl.FromFilename(audioFilePath); if (_player != null) { _player.FinishedPlaying -= DidFinishPlaying; _player.Dispose(); _player = null; } _player = AVAudioPlayer.FromUrl(audioUrl); _player.NumberOfLoops = 0; _player.FinishedPlaying += DidFinishPlaying; return(OperationResult <double> .AsSuccess(_player.Duration)); }
public IObservable <Unit> Play(string name) { Ensure.ArgumentNotNull(name, nameof(name)); return(Observable .Create <Unit>( observer => { var disposables = new CompositeDisposable(); var url = NSBundle.MainBundle.GetUrlForResource(name, "mp3", "Audio"); var audioPlayer = AVAudioPlayer.FromUrl(url); var finishedPlaying = Observable .FromEventPattern <AVStatusEventArgs>(x => audioPlayer.FinishedPlaying += x, x => audioPlayer.FinishedPlaying -= x) .FirstAsync() .Select(_ => Unit.Default) .Publish(); finishedPlaying .Subscribe(observer) .AddTo(disposables); finishedPlaying .ObserveOn(this.scheduler) .Subscribe(_ => audioPlayer.Dispose()) .AddTo(disposables); finishedPlaying .Connect() .AddTo(disposables); audioPlayer.Play(); return disposables; })); }
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(); } }
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); }
public Task PlaySound(string file) { StopSound(); AVAudioSession.SharedInstance().SetCategory(AVAudioSessionCategory.Playback); AVAudioSession.SharedInstance().SetActive(true); var tcs = new TaskCompletionSource <bool>(); _audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(file)); _audioPlayer.DecoderError += (sender, e) => { tcs.TrySetResult(false); }; _audioPlayer.FinishedPlaying += (sender, e) => { tcs.TrySetResult(true); }; if (!_audioPlayer.Play()) { tcs.TrySetResult(false); } _audioPlayingTcs = tcs; return(tcs.Task); }
public override void AwakeFromNib() { playBtnBg = UIImage.FromFile("play.png").StretchableImage(12, 0); pauseBtnBg = UIImage.FromFile("pause.png").StretchableImage(12, 0); _playButton.SetImage(playBtnBg, UIControlState.Normal); _duration.AdjustsFontSizeToFitWidth = true; _currentTime.AdjustsFontSizeToFitWidth = true; _progressBar.MinValue = 0; var fileUrl = NSBundle.MainBundle.PathForResource("sample", "m4a"); player = AVAudioPlayer.FromUrl(new NSUrl(fileUrl, false)); player.FinishedPlaying += delegate(object sender, AVStatusEventArgs e) { if (!e.Status) { Console.WriteLine("Did not complete successfully"); } player.CurrentTime = 0; UpdateViewForPlayerState(); }; player.DecoderError += delegate(object sender, AVErrorEventArgs e) { Console.WriteLine("Decoder error: {0}", e.Error.LocalizedDescription); }; player.BeginInterruption += delegate { UpdateViewForPlayerState(); }; player.EndInterruption += delegate { StartPlayback(); }; _fileName.Text = String.Format("Mono {0} ({1} ch)", Path.GetFileName(player.Url.RelativePath), player.NumberOfChannels); UpdateViewForPlayerInfo(); UpdateViewForPlayerState(); }
public void Speak(System.IO.Stream stream) { if (stream == null) { Debug.WriteLine("Cannot playback empty stream!"); return; } // Save the stream to a file and play it. string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "temp.mp3"); using (stream) using (var file = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None)) { stream.CopyTo(file); } // The AVAudioPlayer instance has to be class scope, otherwise it will stop playing as soon // as it gets collected. this.player = AVAudioPlayer.FromUrl(NSUrl.FromFilename(path)); this.player.FinishedPlaying += (sender, e) => { player = null; }; this.player.PrepareToPlay(); this.player.Play(); }
/// <summary> /// Setups the playback for the test audio file.. /// </summary> /// <returns><c>true</c>, if playback was setup successfully, <c>false</c> otherwise.</returns> private bool SetupPlayback() { var audioSession = AVAudioSession.SharedInstance(); var error = audioSession.SetCategory(AVAudioSessionCategory.Playback); if (error != null) { return(false); } error = audioSession.SetActive(true); if (error != null) { return(false); } var url = NSUrl.FromFilename(Path.Combine(NSBundle.MainBundle.ResourcePath, "test.wav")); try { this.player = AVAudioPlayer.FromUrl(url, out error); } catch { return(false); } this.player.PrepareToPlay(); this.player.MeteringEnabled = true; return(error == null); }
public static void PlayFile(string FileName) { var url = NSUrl.FromFilename(FileName); _player = AVAudioPlayer.FromUrl(url); _player.Play(); }
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)); } }
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(); }
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); }
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(); }; } }
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); }
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!"); }
public Task PlayUrlAsync(Uri url) { var tcs = new TaskCompletionSource <bool>(); using (var player = AVAudioPlayer.FromUrl(new NSUrl(url.ToString()))) Play(player, tcs); return(tcs.Task); }
protected void Init(string FilePath, bool Loop, double Volume) { using (NSUrl url = NSUrl.FromString(FilePath)) _player = AVAudioPlayer.FromUrl(url); _player.NumberOfLoops = Loop? 0: -1; _player.Volume = System.Convert.ToSingle(Volume); //_player.FinishedPlaying += (object sender, AVStatusEventArgs e) => { _player = null; }; }
void _stopButton_TouchDown(object sender, EventArgs e) { _player.StopRecording(); var player = AVAudioPlayer.FromUrl(MonoTouch.Foundation.NSUrl.FromFilename("output.aif")); player.Play(); }
void PlaySoundEffect(string fileName, float volumeLevel) { soundEffectPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(SOUNDS_FOLDER + currentMod + "/" + fileName)); soundEffectPlayer.NumberOfLoops = 0; soundEffectPlayer.Volume = volumeLevel; soundEffectPlayer.Play(); }
void StartPlaying() { var songURL = NSBundle.MainBundle.GetUrlForResource("song", "mp3", "Songs"); player = AVAudioPlayer.FromUrl(songURL); player.FinishedPlaying += PlayerDidFinishPlaying; player.Play(); }
///<Summary> /// Load wave or mp3 audio file from the Android assets folder ///</Summary> public bool Load(string fileName) { DeletePlayer(); player = AVAudioPlayer.FromUrl(NSUrl.FromFilename(fileName)); return(PreparePlayer()); }
public void SetupAudioFile(string filename) { string sFilePath = NSBundle.MainBundle.PathForResource( Path.GetFileNameWithoutExtension(filename), Path.GetExtension(filename)); NSUrl url = NSUrl.FromString(sFilePath); Player = AVAudioPlayer.FromUrl(url); }
public void StartPlayTrack(TrackModel model) { currentTrack = model; _mediaPlayer = AVAudioPlayer.FromUrl(new Foundation.NSUrl(model.Url)); _mediaPlayer.FinishedPlaying += (object sender, AVStatusEventArgs e) => { _mediaPlayer = null; }; _mediaPlayer?.Play(); }
public AudioPlay(string file) { player = AVAudioPlayer.FromUrl(new NSUrl(file)); if (player != null) { player.NumberOfLoops = -1; player.Play(); } }
public void Play(string sound, int repeat = 0) { NSUrl assets = NSUrl.FromString(sound); player = AVAudioPlayer.FromUrl(assets); player.NumberOfLoops = repeat; player.PrepareToPlay(); player.Play(); }
void PlaySound(CLProximity proximity) { string loopFilename = null; int playerIndex = -1, numberOfLoops = -1; float volume = 1f; switch (proximity) { case CLProximity.Far: loopFilename = "Jaws2.mp3"; playerIndex = 0; volume = 5f; break; case CLProximity.Near: loopFilename = "Jaws6-loopable.mp3"; playerIndex = 1; break; case CLProximity.Immediate: loopFilename = "Jaws7.mp3"; numberOfLoops = 0; playerIndex = 2; break; } if (!string.IsNullOrEmpty(loopFilename)) { if (players[playerIndex] == null) { var file = Path.Combine("sounds", loopFilename); var soundUrl = NSUrl.FromFilename(file); players[playerIndex] = AVAudioPlayer.FromUrl(soundUrl); } var player = players [playerIndex]; if (player != null) { player.NumberOfLoops = numberOfLoops; player.Volume = volume; player.PrepareToPlay(); player.Play(); } } for (int i = 0; i < players.Length; i++) { if (i != playerIndex) { if (players[i] != null) { players [i].Stop(); } } } }
public void PlayLaugh() { // http://xamapp.com/playing-sound-with-xamarin-ios/ var soundurl = NSUrl.FromFilename("laugh.mp3"); // http://soundbible.com/2055-Evil-Laugh-Male-6.html var onePlay = AVAudioPlayer.FromUrl(soundurl); //var onePlay = player[playIndex]; onePlay.CurrentTime = 4; // 4 secs; onePlay.Duration*3; onePlay.NumberOfLoops = 1; onePlay.Volume = 1.0f; // onePlay.FinishedPlaying += DidFinishPlaying; onePlay.PrepareToPlay(); onePlay.Play(); try { // HACK: just for Xamarin Insights testing - PlatformNotSupportedException throw new InvalidOperationException("IPlaySound iOS 'invalid'"); } catch (Exception exception) { exception.Data["Type"] = "Pretend sound was not implemented"; // exception.Data["Alarm"] = "Bad char \a"; // BREAKS // exception.Data["Long"] = "0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B123456789C123456789D123456789E123456789F123456789"; // exception.Data["0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B123456789C123456789D123456789E123456789F123456789"] = "was long?"; // exception.Data["Japanese"] = "レストラン–料理店–飲食店"; // exception.Data["Korean"] = "레스토랑–레스토랑–요정"; // exception.Data["Hebrew"] = "מסעדה"; // exception.Data["ChineseT"] ="餐廳–飯店"; // exception.Data["ChineseS"] ="餐厅–酒家"; // exception.Data["レストラン–料理店–飲食店"] = "レストラン–料理店–飲食店"; // exception.Data["레스토랑–레스토랑–요정"] = "레스토랑–레스토랑–요정"; // exception.Data["מסעדה"] = "asdf מסעד"; // exception.Data["餐廳–飯店"] ="餐廳–飯店"; // exception.Data["餐厅–酒家"] ="餐厅–酒家"; Xamarin.Insights.Report(exception, new Dictionary <string, string> { { "Some additional info", "0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B123456789C123456789D123456789E123456789F123456789" }, // {"Newline", "line 1\nline 2"}, //OK // {"Newline", "line 1"+Environment.NewLine+"line 2"}, //OK // {"Null", "null \0"}, //OK // {"Backspace", "bs \b"}, //OK // {"Alarm", "alarm \a"}, //BREAKS - report does not appear in dashboard // {"Japanese", "レストラン–料理店–飲食店"}, // {"Korean", "레스토랑–레스토랑–요정"}, // {"Hebrew", "מסעדה"}, // {"ChineseT","餐廳–飯店"}, // {"ChineseS","餐厅–酒家"}, // {"レストラン–料理店–飲食店", "レストラン–料理店–飲食店レストラン–料理店–飲食店レストラン–料理店–飲食店レストラン–料理店–飲食店レストラン–料理店–飲食店レストラン–料理店–飲食店レストラン–料理店–飲食店"}, // {"레스토랑–레스토랑–요정", "레스토랑–레스토랑–요정레스토랑–레스토랑–요정레스토랑–레스토랑–요정레스토랑–레스토랑–요정레스토랑–레스토랑–요정레스토랑–레스토랑–요정레스토랑–레스토랑–요정레스토랑–레스토랑–요정레스토랑–레스토랑–요정"}, // {"餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店","餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店餐廳飯店"}, // {"餐厅–酒家","餐厅–酒家–餐厅–酒家–餐厅–酒家–餐厅–酒家–餐厅–酒家–餐厅–酒家–餐厅–酒家–餐厅–酒家–餐厅–酒家餐厅–酒家餐厅–酒家餐厅–酒家餐厅–酒家餐厅–酒家餐厅–酒家餐厅–酒家"}, }, Xamarin.Insights.Severity.Error); } }