public async Task <bool> PlayBackgroundMusic(string filename) { // Music enabled? if (!MusicOn || _backgroundMusicLoading) { return(false); } _backgroundMusicLoading = true; // Any existing background music? if (_backgroundMusic != null) { //Stop and dispose of any background music _backgroundMusic.Stop(); _backgroundMusic.Dispose(); } _backgroundSong = filename; // Initialize background music _backgroundMusic = await NewSound(filename, BackgroundMusicVolume, true); _backgroundMusicLoading = false; return(true); }
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(); }
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(); }
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 override void AwakeFromNib () { playBtnBg = UIImage.FromFile ("images/play.png").StretchableImage (12, 0); pauseBtnBg = UIImage.FromFile ("images/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 (); }
/// <summary> /// Pauses the action. /// </summary> /// <param name="item">Item.</param> /// <param name="args">Arguments.</param> private void PauseAction(object item, EventArgs args) { // //UI Update { this.SetToolbarItems(new UIBarButtonItem[] { m_playButton, m_flexItem1, m_recordButton, m_flexItem2, m_trashButton }, true); this.ShowNavigationButton(true); m_recordButton.Enabled = true; m_trashButton.Enabled = true; } // { mplayProgressDisplayLink.Invalidate(); mplayProgressDisplayLink = null; this.NavigationItem.TitleView = null; } // m_audioPlayer.Delegate = null; m_audioPlayer.Stop(); m_audioPlayer = null; AVAudioSession.SharedInstance().SetCategory(new NSString(m_oldSessionCategory)); }
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(); }
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; }
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); }
public void StopSound() { if (_soundPlayer != null && _soundPlayer.Playing) { _soundPlayer.Stop (); _soundPlayer = null; } }
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(); }
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 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 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 }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (this.player != null) { this.player.Dispose(); this.player = null; } if (this.rewindTimer != null) { this.DestroyTimer(this.rewindTimer); this.rewindTimer = null; } if (this.forwardTimer != null) { this.DestroyTimer(this.forwardTimer); this.forwardTimer = null; } if (this.updateTimer != null) { this.DestroyTimer(this.updateTimer); this.updateTimer = null; } }
public void Play(byte[] data) { AVAudioPlayer player = AVAudioPlayer.FromData(NSData.FromArray(data)); player.PrepareToPlay(); 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)); } }
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); } }
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(); } } }); }
public static void PlayFile(string FileName) { var url = NSUrl.FromFilename(FileName); _player = AVAudioPlayer.FromUrl(url); _player.Play(); }
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(); } }
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); }
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)); } }
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(); }
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(); }
protected void Init(Stream Content, bool Loop, double Volume) { _player = AVAudioPlayer.FromData(NSData.FromStream(Content)); _player.NumberOfLoops = Loop? 0: -1; _player.Volume = System.Convert.ToSingle(Volume); //_player.FinishedPlaying += (object sender, AVStatusEventArgs e) => { _player = null; }; }
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(); } } }
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 } }
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 Dispose(bool disposing) { if (!disposed) { if (disposing) { #if WINDOWS_MEDIA_SESSION if (_topology != null) { _topology.Dispose(); _topology = null; } #elif !WINDOWS_MEDIA_ENGINE if (_sound != null) { #if IOS _sound.FinishedPlaying -= OnFinishedPlaying; #endif _sound.Dispose(); _sound = null; } #endif } disposed = true; } }
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); }
public ObjectsProcessor(List <string> supported_sounds, List <string> supported_recordings) { client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey)) { Endpoint = endpoint }; busy = false; analysis = new ImageAnalysis(); NSError err; // init of audio players foreach (string tag in supported_sounds) { tags_to_sounds[tag] = new AVAudioPlayer(NSUrl.FromFilename($"sounds/{tag}.wav"), "", out err); //enables custem play rate. 2.0 playrate == twice the playback speed tags_to_sounds[tag].EnableRate = true; tags_to_sounds[tag].Volume = 1.0f; } foreach (string supported_recording in supported_recordings) { NSData song = NSData.FromUrl(NSUrl.FromFilename(Utils.GetFileName(supported_recording)), NSDataReadingOptions.Uncached, out NSError errr); tags_to_sounds[supported_recording] = new AVAudioPlayer( song, "", out err ); tags_to_sounds[supported_recording].Volume = 1.0f; tags_to_sounds[supported_recording].EnableRate = true; } }
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 AudioPlay(string file) { player = AVAudioPlayer.FromUrl (new NSUrl (file)); if (player != null){ player.NumberOfLoops = -1; player.Play (); } }
public void StopAudioPlayback() { if (_player != null) { _player.Stop(); _player.Dispose(); _player = null; } }
private void PlatformDispose(bool disposing) { if (_sound == null) return; _sound.FinishedPlaying -= OnFinishedPlaying; _sound.Dispose(); _sound = null; }
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 void BeginInterruption(AVAudioPlayer p) { Console.WriteLine (@"Interruption begin. Updating UI for new state"); // the object has already been paused, we just need to update UI if (inBackground) { this.updateViewForPlayerStateInBackground (p); } else { this.updateViewForPlayerState (p); } }
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); }
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; } }
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 (); }
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"); } }
public Task<SoundFile> SetMediaAsync (string filename) { return Task.Run<SoundFile> (() => { _currentFile = new SoundFile (); _currentFile.Filename = filename; NSUrl url = NSUrl.FromFilename (_currentFile.Filename); player = AVAudioPlayer.FromUrl (url); player.FinishedPlaying += (object sender, AVStatusEventArgs e) => { if (e.Status) { this.OnFileFinished (new SoundFinishedEventArgs (this._currentFile)); } }; _currentFile.Duration = TimeSpan.FromSeconds (player.Duration); return _currentFile; }); }
AudioPlayerController(string url) { Url = url; try { _localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); _localPath = Path.Combine(_localPath, "AudioBuffer.mp3"); if (File.Exists(_localPath)) { File.Delete(_localPath); } StartDownloading(); } catch (Exception ex) { _player = null; Console.WriteLine ("! " + ex.ToString()); } }
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)); } }
public MiniPadView (RectangleF frame): base(frame) { var image = UIImage.FromBundle ("iPadImage.png"); Frame = new RectangleF (Frame.Location, image.Size); ClipsToBounds = false; var imageView = new UIImageView (image); AddSubview (imageView); zombies = new List <WalkingDead> (); var audioNewZombie = NSUrl.FromFilename ("NewZombie.mp3"); var audioRemoveZombie = NSUrl.FromFilename ("RemoveZombie.mp3"); newZombieSound = AVAudioPlayer.FromUrl (audioNewZombie); removeZombieSound = AVAudioPlayer.FromUrl (audioRemoveZombie); }
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 { } }
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(); }
public override void AwakeFromNib () { base.AwakeFromNib (); var fileUrl = NSBundle.MainBundle.PathForResource ("sample", "m4a"); _player = AVAudioPlayer.FromUrl (new NSUrl (fileUrl, false)); _player.FinishedPlaying += (sender, e) => { if (!e.Status) { Console.WriteLine ("Did not complete successfully"); } _player.CurrentTime = 0; UpdateViewForPlayerState (); }; SetSharedInstanceForRemoteControl (); }
public Task PlaySoundAsync(string filename) { var tcs = new TaskCompletionSource<bool> (); string path = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(filename), Path.GetExtension(filename)); var url = NSUrl.FromString (path); _player = AVAudioPlayer.FromUrl(url); _player.FinishedPlaying += (object sender, AVStatusEventArgs e) => { _player = null; tcs.SetResult(true); }; _player.Play(); return tcs.Task; }
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); } }
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!"); } }
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 (); }
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; } }
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); } }
public static void PlaySound(string soundurl) { if (soundurl == string.Empty) return; if (player != null) { player.Stop (); } try { //var file = Path.Combine("sounds", filename); NSData data = NSData.FromUrl(NSUrl.FromString(soundurl)); player = AVAudioPlayer.FromData (data); var onePlay = player; onePlay.CurrentTime = onePlay.Duration * 2; onePlay.NumberOfLoops = 1; onePlay.Volume = 1.0f; onePlay.FinishedPlaying += DidFinishPlaying; onePlay.PrepareToPlay (); onePlay.Play (); } catch (Exception e) { //LogLine ("PlaySound: Error: " + e.Message, true); } }
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)); }
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(); } }
private void ResetMusicPlayer() { currentMusic = null; if (audioPlayer != null) { audioPlayer.Dispose(); audioPlayer = null; } }
public void Dispose () { if (_player != null) _player.Dispose (); _player = null; }