public void playAudio(string filePath) { if (player != null) { player.Pause(); } player = AVPlayer.FromUrl(new NSUrl(filePath)); player.Play(); }
public void PlayRecording() { try { Console.WriteLine("Playing Back Recording " + this.audioFilePath.ToString()); // The following line prevents the audio from stopping // when the device autolocks. will also make sure that it plays, even // if the device is in mute NSError error = null; AVAudioSession.SharedInstance().SetCategory(AVAudioSession.CategoryPlayback, out error); if (error != null) { throw new Exception(error.DebugDescription); } //AudioSession.Category = AudioSessionCategory.MediaPlayback; this.player = new AVPlayer(this.audioFilePath); this.player.Play(); } catch (Exception ex) { Console.WriteLine("There was a problem playing back audio: "); Console.WriteLine(ex.Message); } }
protected override void OnElementChanged(ElementChangedEventArgs <View> e) { base.OnElementChanged(e); //Get the video //bubble up to the AVPlayerLayer //var url = new NSUrl ("http://www.androidbegin.com/tutorial/AndroidCommercial.3gp"); var url = new NSUrl("file://" + NSBundle.MainBundle.PathForResource("SampleVideo", "mp4")); _asset = AVAsset.FromUrl(url); _playerItem = new AVPlayerItem(_asset); _player = new AVPlayer(_playerItem); _playerLayer = AVPlayerLayer.FromPlayer(_player); //Create the play button playButton = new UIButton(); playButton.SetTitle("Play Video", UIControlState.Normal); playButton.BackgroundColor = UIColor.Gray; //Set the trigger on the play button to play the video playButton.TouchUpInside += (object sender, EventArgs arg) => { _player.Play(); }; }
private void TryDisposePlayer() { if (_player != null) { try { _videoLayer.RemoveObserver(this, new NSString("videoRect"), _videoLayer.Handle); _videoLayer.RemoveFromSuperLayer(); _player.CurrentItem?.RemoveObserver(this, new NSString("loadedTimeRanges"), _player.Handle); _player.CurrentItem?.RemoveObserver(this, new NSString("status"), _player.Handle); _player.CurrentItem?.RemoveObserver(this, new NSString("duration"), _player.Handle); _player.RemoveObserver(this, new NSString("rate"), RateObservationContext.Handle); _player.RemoveTimeObserver(_periodicTimeObserverObject); } finally { _itemFailedToPlayToEndTimeNotification?.Dispose(); _playbackStalledNotification?.Dispose(); _didPlayToEndTimeNotification?.Dispose(); _videoLayer?.Dispose(); _player?.CurrentItem?.Dispose(); _player?.Dispose(); _player = null; } } }
public AudioPlayerImplementation() { _player = new AVPlayer() { ActionAtItemEnd = AVPlayerActionAtItemEnd.None }; }
protected override void OnElementChanged(ElementChangedEventArgs <VideoView> e) { if (e.NewElement != null) { if (string.IsNullOrEmpty(Element.Source)) { throw new ArgumentException("Source is required."); } if (base.Control == null) { var view = new UIView(); SetNativeControl(view); if (Element.ShowControl) { if (Element.IsFromUrl) { if (movieController == null) { var url = NSUrl.FromString(Element.Source); movieController = new MPMoviePlayerController(); movieController.ShouldAutoplay = true; movieController.Fullscreen = true; movieController.ControlStyle = MPMovieControlStyle.Embedded; movieController.PrepareToPlay(); movieController.SourceType = MPMovieSourceType.Streaming; movieController.ContentUrl = url; view.Add(movieController.View); movieController.Play(); movieController.SetFullscreen(true, true); } } } else { if (playerItem == null) { asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source)); playerItem = new AVPlayerItem(asset); // AVPlayerItem.DidPlayToEndTimeNotification; player = new AVPlayer(playerItem); player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None; playerLayer = AVPlayerLayer.FromPlayer(player); view.Layer.AddSublayer(playerLayer); SetRepeat(); SetPlaying(); } } } } base.OnElementChanged(e); }
protected override void OnElementChanged(ElementChangedEventArgs <VideoPlayer> args) { base.OnElementChanged(args); if (args.NewElement != null) { if (Control == null) { player = new AVPlayer(); _playerViewController = new AVPlayerViewController { Player = player, ShowsPlaybackControls = false }; SetNativeControl(_playerViewController.View); } UpdateBackground(); UpdateSource(); UpdatePlayback(); args.NewElement.ResetToStartRequested += OnResetToStartRequested; } if (args.OldElement != null) { args.OldElement.ResetToStartRequested -= OnResetToStartRequested; } }
protected override void OnElementChanged(ElementChangedEventArgs <VideoPlayer> e) { base.OnElementChanged(e); if (e.NewElement != null) { if (Control == null) { _playerViewController = new AVPlayerViewController() { ShowsPlaybackControls = true }; _player = new AVPlayer(); _playerViewController.Player = _player; SetNativeControl(_playerViewController.View); } if (e.NewElement.Source is VideoPlayer.FileSource fileSource) { _playerItem = new AVPlayerItem(new NSUrl(fileSource.Path)); } else if (e.NewElement.Source is VideoPlayer.UrlSource urlSource) { _playerItem = new AVPlayerItem(new NSUrl(urlSource.Url)); } _player.ReplaceCurrentItemWithPlayerItem(_playerItem); } if (e.OldElement != null) { } }
public override void ViewDidLoad() { base.ViewDidLoad(); VideoLocal.Layer.CornerRadius = 10; VideoInternet.Layer.CornerRadius = 10; VideoLocal.TouchUpInside += delegate { AVPlayer Reproductor; AVPlayerLayer CapaRedproductor; AVAsset Recurso; AVPlayerItem RecursoReproducir; Recurso = AVAsset.FromUrl(NSUrl.FromFilename("toystory.mp4")); RecursoReproducir = new AVPlayerItem(Recurso); Reproductor = new AVPlayer(RecursoReproducir); CapaRedproductor = AVPlayerLayer.FromPlayer(Reproductor); CapaRedproductor.Frame = new CGRect(50, 100, 300, 300); View.Layer.AddSublayer(CapaRedproductor); Reproductor.Play(); }; VideoInternet.TouchUpInside += delegate { AVPlayer Reproductor; AVPlayerLayer CapaRedproductor; AVAsset Recurso; AVPlayerItem RecursoReproducir; Recurso = AVAsset.FromUrl(NSUrl.FromString("https://www.rmp-streaming.com/media/bbb-360p.mp4")); RecursoReproducir = new AVPlayerItem(Recurso); Reproductor = new AVPlayer(RecursoReproducir); CapaRedproductor = AVPlayerLayer.FromPlayer(Reproductor); CapaRedproductor.Frame = new CGRect(50, 100, 300, 300); View.Layer.AddSublayer(CapaRedproductor); Reproductor.Play(); }; }
private void SetupUserInterface() { var playerUrl = new NSUrl((Element as ViewPlayerPage).Url); playerView = new AVPlayerViewController(); var playerItem = new AVPlayerItem(playerUrl); player = new AVPlayer(playerItem); //var layer = new AVPlayerLayer(); ////给AVPlayer一个播放的layer层 //layer.Player = player; //layer.Frame = new CoreGraphics.CGRect(0, 100, View.Frame.Size.Width, 600); //layer.BackgroundColor = UIColor.Gray.CGColor; ////设置AVPlayer的填充模式 //layer.VideoGravity = AVLayerVideoGravity.Resize; //View.Layer.AddSublayer(layer); //player.Play(); playerView.View.Frame = new CoreGraphics.CGRect(0, (View.Frame.Size.Height - 320) / 2, View.Frame.Size.Width, 320); playerView.ShowsPlaybackControls = true; playerView.Player = player; playerView.View.TranslatesAutoresizingMaskIntoConstraints = true; View.AddSubview(playerView.View); ViewController.PresentViewController(playerView, true, null); player.Play(); }
public override void ViewDidLoad() { base.ViewDidLoad(); _asset = AVAsset.FromUrl(NSUrl.FromFilename("SampleVideo.mp4")); _playerItem = new AVPlayerItem(_asset); _playerItem.SeekingWaitsForVideoCompositionRendering = true; _playerItem.AddObserver(this, (NSString)"status", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle); NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, (notification) => { Console.WriteLine("Seek Zero = true"); seekToZeroBeforePlaying = true; this.updatePlayPauseButton(); }, _playerItem); _player = new AVPlayer(_playerItem); _playerLayer = AVPlayerLayer.FromPlayer(_player); _playerLayer.Frame = this.playerView.Frame; this.playerView.Layer.AddSublayer(_playerLayer); updateScrubber(); updateTimeLabel(); slider.EditingDidBegin += slider_EditingDidBegin; slider.EditingDidEnd += slider_EditingDidEnd; slider.ValueChanged += slider_ValueChanged; playpauseButton.TouchUpInside += playpauseButton_TouchUpInside; playing = true; _player.Play(); }
static AVAssetTrack FetchFirstAudioTrack(AVPlayer player) { AVAssetTrack[] tracks = player.CurrentItem.Asset.Tracks; AVAssetTrack firstAudioTrack = tracks.FirstOrDefault(t => t.MediaType == AVMediaType.Audio); return(firstAudioTrack); }
private void InitializePlayer() { _player = new AVPlayer(); _videoLayer = AVPlayerLayer.FromPlayer(_player); var avSession = AVAudioSession.SharedInstance(); // By setting the Audio Session category to AVAudioSessionCategorPlayback, audio will continue to play when the silent switch is enabled, or when the screen is locked. avSession.SetCategory(AVAudioSessionCategory.Playback); NSError activationError = null; avSession.SetActive(true, out activationError); if (activationError != null) { Console.WriteLine("Could not activate audio session {0}", activationError.LocalizedDescription); } Player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate { var totalDuration = TimeSpan.FromSeconds(_player.CurrentItem.Duration.Seconds); var totalProgress = Position.TotalMilliseconds / totalDuration.TotalMilliseconds; PlayingChanged?.Invoke(this, new PlayingChangedEventArgs(totalProgress, Position, Duration)); }); }
// Load movies and display movie layers private AVPlayerLayer ConfigurePlayer(string movieName, string hostingNodeName) { var player = AVPlayer.FromUrl(NSUrl.FromFilename(movieName)); player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None; // loop NSNotificationCenter.DefaultCenter.AddObserver(this, new Selector("PlayerItemDidReachEnd"), AVPlayerItem.DidPlayToEndTimeNotification, player.CurrentItem); player.Play(); // Set an arbitrary frame. This frame will be the size of our movie texture so if it is too small it will appear scaled up and blurry, and if it is too big it will be slow var playerLayer = new AVPlayerLayer(); playerLayer.Player = player; playerLayer.ContentsGravity = AVPlayerLayer.GravityResizeAspectFill; playerLayer.Frame = new CGRect(0, 0, 600, 800); // Use a parent layer with a background color set to black // That way if the movie is stil loading and the frame is transparent, we won't see holes in the model var backgroundLayer = CALayer.Create(); backgroundLayer.BackgroundColor = NSColor.Black.CGColor; backgroundLayer.Frame = new CGRect(0, 0, 600, 800); backgroundLayer.AddSublayer(playerLayer); var frameNode = GroundNode.FindChildNode(hostingNodeName, true); var material = frameNode.Geometry.Materials [1]; material.Diffuse.Contents = backgroundLayer; return(playerLayer); }
public AVMediaPlayer() { player = new AVPlayer { ActionAtItemEnd = AVPlayerActionAtItemEnd.Pause, #if __IOS__ AllowsAirPlayVideo = true, #endif AllowsExternalPlayback = true, Volume = Settings.CurrentVolume, }; resourceDelegate = new MyResourceLoaderDelegate(this); timeObserver = player.AddPeriodicTimeObserver(new CoreMedia.CMTime(5, 30), null, (time) => OnPlabackTimeChanged(player, time)); rateObserver = player.AddObserver("rate", NSKeyValueObservingOptions.New, (change) => OnStateChanged(player)); PlayerLayer = AVPlayerLayer.FromPlayer(player); endTimeObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, (notification) => { var avplayerItem = notification?.Object as AVPlayerItem; if (avplayerItem == player.CurrentItem) { OnFinished(avplayerItem); } }); playerDidStallObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.PlaybackStalledNotification, (notification) => { var avplayerItem = notification?.Object as AVPlayerItem; if (avplayerItem == player.CurrentItem) { Console.WriteLine("Handle STalling"); isStalled = true; State = PlaybackState.Buffering; } }); }
public override void ViewDidLoad () { base.ViewDidLoad (); LoadNotifications (); IsSeeking = false; _asset = AVAsset.FromUrl (NSUrl.FromFilename ("sample.m4v")); _playerItem = new AVPlayerItem (_asset); _player = new AVPlayer (_playerItem); _playerItem.AddObserver (this, (NSString)"status", NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle); _playerItem.AddObserver (this, (NSString)"playbackBufferFull", NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, PlaybackBufferFullContext.Handle); _playerItem.AddObserver (this, (NSString)"playbackBufferEmpty", NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, PlaybackBufferEmptyContext.Handle); _playerItem.AddObserver (this, (NSString)"playbackLikelyToKeepUp", NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Initial, PlaybackLikelyToKeepUpContext.Handle); _player.Muted = true; _playerLayer = AVPlayerLayer.FromPlayer (_player); _playerLayer.Frame = View.Frame; View.Layer.AddSublayer (_playerLayer); AddTapGesture (); InitScrubberTimer (); SyncScrubber (); _player.Play (); PlayButton.SetTitle ("Pause", UIControlState.Normal); }
protected override void OnElementChanged(ElementChangedEventArgs <CustomSlider> e) { base.OnElementChanged(e); if (Control == null) { seekBar = new UISlider(); SetNativeControl(seekBar); } if (e.OldElement != null) { if (player != null) { player.Dispose(); playerItem.Dispose(); player = null; playerItem = null; } /* * player.RemoveObserver(this, "status"); * * player.CurrentItem?.RemoveObserver(this, (NSString)"playbackBufferEmpty"); * player.CurrentItem?.RemoveObserver(this, (NSString)"playbackLikelyToKeepUp"); */ } if (e.NewElement != null) { slider = e.NewElement; seekBar.MaximumTrackTintColor = Color.FromHex(slider.MaximumTrackTintColor).ToUIColor(); seekBar.MinimumTrackTintColor = Color.FromHex(slider.MinimumTrackTintColor).ToUIColor(); //seekBar.ThumbTintColor = Color.FromHex("#827DCE").ToUIColor(); seekBar.SetThumbImage(UIImage.FromFile(slider.TintImageFileName), UIControlState.Normal); seekBar.Continuous = false; seekBar.SizeToFit(); _fitSize = Control.Bounds.Size; // except if your not running iOS 7... then it fails... if (_fitSize.Width <= 0 || _fitSize.Height <= 0) { _fitSize = new SizeF(22, 22); // Per the glorious documentation known as the SDK docs } //if(e.OldElement != null) // slider.ClickedButton -= Slider_ClickedButton; slider.ClickAction = UpdatePlaying; slider.StopPlayingAction = StopPlayingAction; // Control.ScaleY = 5; slider.CommandImageFileName = slider.PlayImageFileName; slider.CommandText = "Play"; //slider.AudioService.IsStoped = true; slider.TimeLeftString = string.Format("{0:mm\\:ss}", TimeSpan.FromMilliseconds(slider.FileDuration ?? 0)); } seekBar.TouchDown += Control_TouchDown; seekBar.TouchUpInside += Control_TouchUpInside; }
protected override void OnElementChanged (ElementChangedEventArgs<View> e) { base.OnElementChanged (e); //Get the video //bubble up to the AVPlayerLayer var url = new NSUrl ("http://www.androidbegin.com/tutorial/AndroidCommercial.3gp"); _asset = AVAsset.FromUrl (url); _playerItem = new AVPlayerItem (_asset); _player = new AVPlayer (_playerItem); _playerLayer = AVPlayerLayer.FromPlayer (_player); //Create the play button playButton = new UIButton (); playButton.SetTitle ("Play Video", UIControlState.Normal); playButton.BackgroundColor = UIColor.Gray; //Set the trigger on the play button to play the video playButton.TouchUpInside += (object sender, EventArgs arg) => { _player.Play(); }; }
public void InitFile(string pathToAudioFile) { if (Player != null) { Stop(); IsStoped = true; IsCompleted = true; } if (string.IsNullOrWhiteSpace(pathToAudioFile)) { throw new Exception("No file specified to play"); } //http://192.168.0.95:50000/api/Post/GetFileByName?fileName=2556bc1b-f6e7-4bd8-8984-d046b677ccf2&type=2 using (var url = NSUrl.FromString(pathToAudioFile)) { var testURL = NSUrl.FromString("https://s3.amazonaws.com/kargopolov/kukushka.mp3"); PlayerItem = AVPlayerItem.FromUrl(url); if (Player == null) { Player = new AVPlayer(PlayerItem); if (Player == null) { return; } } videoEndNotificationToken = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, VideoDidFinishPlaying, PlayerItem); } }
public override void ViewDidLoad() { base.ViewDidLoad(); var audioSession = AVAudioSession.SharedInstance(); audioSession.SetCategory(AVAudioSessionCategory.Playback); audioSession.OutputChannelsChanged += (sender, e) => Console.WriteLine("Output channels changed"); audioSession.SetActive(true); // This is not working... MPRemoteCommandCenter rcc = MPRemoteCommandCenter.Shared; rcc.SeekBackwardCommand.Enabled = false; rcc.SeekForwardCommand.Enabled = false; rcc.NextTrackCommand.Enabled = false; rcc.PreviousTrackCommand.Enabled = false; rcc.SkipBackwardCommand.Enabled = false; rcc.SkipForwardCommand.Enabled = false; // You must enable a command so that others can be disabled? // See http://stackoverflow.com/a/28925369. rcc.PlayCommand.Enabled = true; MPNowPlayingInfo nowPlayingInfo = new MPNowPlayingInfo(); nowPlayingInfo.AlbumTitle = "Vermont"; nowPlayingInfo.Artist = "Colchester"; nowPlayingInfo.Title = "VPR"; MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = nowPlayingInfo; AVPlayer player = new AVPlayer(audioUrl); player.Play(); }
protected override void OnElementChanged(ElementChangedEventArgs <VideoPlayer> e) { base.OnElementChanged(e); if (Control == null) { _timer = new Timer(TimeSpan.FromSeconds(1).TotalMilliseconds); _timer.Elapsed += _timer_Elapsed; } if (e.OldElement != null) { _timer?.Stop(); _timer?.Dispose(); _timer = null; _asset?.Dispose(); _asset = null; _playerItem?.Dispose(); _playerItem = null; _player?.Dispose(); _player = null; _playerLayer?.Dispose(); _playerLayer = null; } if (e.NewElement != null) { } }
partial void DidTapPlay(UIBarButtonItem sender) { if (_Player != null) { if (_Player.TimeControlStatus == AVPlayerTimeControlStatus.Playing) { return; } _Player.Play(); } else { try { var songURL = NSBundle.MainBundle.GetUrlForResource("song", "mp3", "Songs"); _Player = AVPlayer.FromUrl(songURL); _KVOController.Observe(_Player, "timeControlStatus", NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, PlayerStatusDidChange); _Player.Play(); } catch (Exception ex) { var alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("Dismiss", UIAlertActionStyle.Cancel, null)); PresentViewController(alert, true, null); } } }
public async override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); var url = new NSUrl(CurrentPodcastEpisode.AudioUrl); player = AVPlayer.FromUrl(url); var updated = await CurrentPodcastEpisode.GetTimeAsync(); if (updated == null || updated.ShowNumber != CurrentPodcastEpisode.ShowNumber) { return; } if (player == null || player.Status != AVPlayerStatus.ReadyToPlay) { startTime = updated.CurrentTime; return; } await player.SeekAsync(CMTime.FromSeconds(updated.CurrentTime, 1)); timer_Elapsed(null, null);//update UI }
///<Summary> /// Load wave or mp3 audio file from the Android assets folder ///</Summary> public bool Load(string fileName) { DeletePlayer(); NSError error = new NSError(); try { if (!String.IsNullOrWhiteSpace(fileName)) { string directory = Path.GetDirectoryName(fileName); string filename = Path.GetFileNameWithoutExtension(fileName); string extension = Path.GetExtension(fileName).Substring(1); NSUrl url = NSBundle.MainBundle.GetUrlForResource(filename, extension, directory); avasset = AVAsset.FromUrl(url); avplayerItem = new AVPlayerItem(avasset); avplayerItem.AudioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.Varispeed; avplayer = new AVPlayer(avplayerItem); NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, (obj) => { avplayer.Seek(CoreMedia.CMTime.Zero); avplayer.PlayImmediatelyAtRate(_rate); obj.Dispose(); }, avplayer.CurrentItem); } } catch (Exception e) { return(false); } return(true); }
private async Task SetSource(AtomVideoSource source) { try { asset = await LoadAsset(source); playerItem = new AVPlayerItem(asset); player = new AVPlayer(playerItem); playerController = new AVPlayerViewController(); Control.AddSubview(playerController.View); playerController.Player = player; playerController.View.Frame = Control.Frame; player.Seek(CMTime.FromSeconds(1, 1000)); if (Element.IsPlaying) { player.Play(); } } catch (Exception ex) { AtomDevice.Instance.Log(ex); } }
void SetUpContentPlayer() { var contentURL = new Foundation.NSUrl(contentUrlString); AVPlayer player = new AVPlayer(contentURL); aVPlayerViewController = new AVPlayerViewController(); aVPlayerViewController.Player = player; // Set up your content playhead and contentComplete callback. contentPlayhead = new IMAAVPlayerContentPlayhead(player); NSNotificationCenter.DefaultCenter.AddObserver(new NSString("AVPlayerItemDidPlayToEndTime"), ContentDidFinishPlaying); //NSNotificationCenter.DefaultCenter.AddObserver(this // , new ObjCRuntime.Selector("ViewController.contentDidFinishPlaying(_:)") // , new NSString("AVPlayerItemDidPlayToEndTime") // , player.CurrentItem) ; // contentPlayhead = IMAAVPlayerContentPlayhead(avPlayer: player) //NotificationCenter.default.addObserver( // self, // selector: #selector(ViewController.contentDidFinishPlaying(_:)), // name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, // object: player.currentItem); ShowContentPlayer(); }
void UpdateSource() { if (MediaElement.Source != null) { AVAsset asset = null; if (MediaElement.Source.Scheme == "ms-appx") { // used for a file embedded in the application package asset = AVAsset.FromUrl(NSUrl.FromFilename(MediaElement.Source.LocalPath.Substring(1))); } else if (MediaElement.Source.Scheme == "ms-appdata") { string filePath = ResolveMsAppDataUri(MediaElement.Source); if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException("Invalid Uri", "Source"); } asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath)); } else { asset = AVUrlAsset.Create(NSUrl.FromString(MediaElement.Source.AbsoluteUri), GetOptionsWithHeaders(MediaElement.HttpHeaders)); } AVPlayerItem item = new AVPlayerItem(asset); RemoveStatusObserver(); _statusObserver = (NSObject)item.AddObserver("status", NSKeyValueObservingOptions.New, ObserveStatus); if (Player != null) { Player.ReplaceCurrentItemWithPlayerItem(item); Player.Volume = (float)MediaElement.Volume; } else { Player = new AVPlayer(item); _rateObserver = (NSObject)Player.AddObserver("rate", NSKeyValueObservingOptions.New, ObserveRate); Player.Volume = (float)MediaElement.Volume; } if (MediaElement.AutoPlay) { Play(); } } else { if (MediaElement.CurrentState == MediaElementState.Playing || MediaElement.CurrentState == MediaElementState.Buffering) { Player.Pause(); Controller.CurrentState = MediaElementState.Stopped; } } }
public override void ViewDidLoad() { base.ViewDidLoad(); string path = NSBundle.MainBundle.PathForResource("Dramatic2", "m4a"); if (path != null) { memeEffect = AVPlayer.FromUrl(NSUrl.FromFilename(path)); memeEffect.AddObserver(this, (NSString)"rate", (NSKeyValueObservingOptions)0, MemePlaybackContext); } path = NSBundle.MainBundle.PathForResource("Sosumi", "wav"); if (path != null) { beepEffect = AVPlayer.FromUrl(NSUrl.FromFilename(path)); } setupAVCapture(); if (MaxZoom == 1f && device != null) { displayErrorOnMainQueue(null, "Device does not support zoom"); slider.Enabled = false; } }
private void PlatformInitialize() { var err = new NSError(); movie = AVPlayerItem.FromUrl(NSUrl.FromFilename(FileName)); Player = new AVPlayer(movie); }
protected override void OnElementChanged(ElementChangedEventArgs <VideoPlayer> args) { base.OnElementChanged(args); if (args.NewElement != null) { if (Control == null) { // Create AVPlayerViewController _playerViewController = new AVPlayerViewController(); // Set Player property to AVPlayer player = new AVPlayer(); _playerViewController.Player = player; // Use the View from the controller as the native control SetNativeControl(_playerViewController.View); } SetSource(); args.NewElement.UpdateStatus += OnUpdateStatus; args.NewElement.PlayRequested += OnPlayRequested; args.NewElement.PauseRequested += OnPauseRequested; args.NewElement.StopRequested += OnStopRequested; } if (args.OldElement != null) { args.OldElement.UpdateStatus -= OnUpdateStatus; args.OldElement.PlayRequested -= OnPlayRequested; args.OldElement.PauseRequested -= OnPauseRequested; args.OldElement.StopRequested -= OnStopRequested; } }
public static VideoHandle Create(string uri, Action loaded, Action <string> error) { var handle = new VideoHandle(); var url = new NSUrl(uri); handle.Asset = new AVUrlAsset(url, (AVUrlAssetOptions)null); handle.Asset.LoadValuesAsynchronously(new string[] { "tracks" }, () => DispatchQueue.MainQueue.DispatchAsync( () => { NSError e; var status = handle.Asset.StatusOfValue("tracks", out e); if (status == AVKeyValueStatus.Loaded) { handle.Output = new AVPlayerItemVideoOutput( new CVPixelBufferAttributes { PixelFormatType = CVPixelFormatType.CV32BGRA, }); handle.PlayerItem = AVPlayerItem.FromAsset(handle.Asset); handle.PlayerItem.AddOutput(handle.Output); handle.Player = AVPlayer.FromPlayerItem(handle.PlayerItem); PollReadyState(handle, loaded, error); } else { error("Failed to load: " + status.ToString()); } })); return(handle); }
protected override void OnElementChanged(ElementChangedEventArgs <VideoPlayerView> e) { base.OnElementChanged(e); if (e.NewElement != null) { if (Control == null) { // Create AVPlayerViewController _playerViewController = new AVPlayerViewController { //ExitsFullScreenWhenPlaybackEnds = true }; // Set Player property to AVPlayer _player = new AVPlayer(new NSUrl(Element.Source)); _playerViewController.Player = _player; // Use the View from the controller as the native control SetNativeControl(_playerViewController.View); } _videoPlayer = e.NewElement; } if (e.OldElement != null) { } }
void StateChanged(AVPlayer player) { if (player == CurrentPlayer) { Parent.State = player.Rate == 0 ? PlaybackState.Paused : PlaybackState.Playing; } }
private void InitPlayer() { if (player != null) player.Pause(); player = AVPlayer.FromUrl(new NSUrl(Player.Url)); player.Play(); timer.Start(); }
private void PlatformDispose(bool disposing) { if (_sound == null) return; playToEndObserver.Dispose (); playToEndObserver = null; _sound.Dispose(); _sound = null; _player.Dispose(); _player = null; }
public override void ViewDidLoad () { base.ViewDidLoad (); _asset = AVAsset.FromUrl (NSUrl.FromFilename ("sample.m4v")); _playerItem = new AVPlayerItem (_asset); _player = new AVPlayer (_playerItem); _playerLayer = AVPlayerLayer.FromPlayer (_player); _playerLayer.Frame = View.Frame; View.Layer.AddSublayer (_playerLayer); _player.Play (); }
public override void AwakeFromNib() { base.AwakeFromNib(); _asset = AVAsset.FromUrl(NSUrl.FromFilename("video.mp4")); _playerItem = new AVPlayerItem(_asset); _player = new AVPlayer(_playerItem); image = new UIImageView(UIImage.FromFile("Icon-76.png")); label.Font = UIFont.FromName("Cochin-BoldItalic", 22f); label.TextColor = UIColor.FromRGB(127, 51, 0); label.BackgroundColor = UIColor.Clear; LayoutIfNeeded(); _playerLayer = AVPlayerLayer.FromPlayer(_player); _player.ExternalPlaybackVideoGravity = AVLayerVideoGravity.ResizeAspectFill; }
public override void RemoteControlReceived(UIEvent theEvent) { if (theEvent.Type != UIEventType.RemoteControl) { return; } Debug.WriteLine("Received remote control event: " + theEvent.Subtype); switch (theEvent.Subtype) { case UIEventSubtype.RemoteControlTogglePlayPause: if (player?.Rate > 0 && player.Error == null) // player is playing { player.Pause(); player.Dispose(); playPauseButton.SetTitle("Play", UIControlState.Normal); } else { player = new AVPlayer(source); player.Play(); playPauseButton.SetTitle("Stop", UIControlState.Normal); } break; case UIEventSubtype.RemoteControlPause: case UIEventSubtype.RemoteControlStop: player.Pause(); player.Dispose(); playPauseButton.SetTitle("Play", UIControlState.Normal); break; case UIEventSubtype.RemoteControlPlay: case UIEventSubtype.RemoteControlPreviousTrack: case UIEventSubtype.RemoteControlNextTrack: // only handle these cases if player not already playing if (!(player?.Rate > 0) && player.Error == null) { player = new AVPlayer(source); player.Play(); playPauseButton.SetTitle("Stop", UIControlState.Normal); } break; } }
private void InitializePlayer() { _player = new AVPlayer(); AVAudioSession avSession = AVAudioSession.SharedInstance(); // By setting the Audio Session category to AVAudioSessionCategorPlayback, audio will continue to play when the silent switch is enabled, or when the screen is locked. avSession.SetCategory(AVAudioSessionCategory.Playback); NSError activationError = null; avSession.SetActive(true, out activationError); if (activationError != null) { Console.WriteLine("Could not activate audio session {0}", activationError.LocalizedDescription); } player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate(CMTime time) { OnPlaying(EventArgs.Empty); }); }
static AVAssetTrack FetchFirstAudioTrack (AVPlayer player) { AVAssetTrack[] tracks = player.CurrentItem.Asset.Tracks; AVAssetTrack firstAudioTrack = tracks.FirstOrDefault (t => t.MediaType == AVMediaType.Audio); return firstAudioTrack; }
private void InitializePlayer() { _player = new AVPlayer(); _videoLayer = AVPlayerLayer.FromPlayer(_player); NSError activationError = null; if (activationError != null) Console.WriteLine("Could not activate audio session {0}", activationError.LocalizedDescription); Player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate { var totalDuration = TimeSpan.FromSeconds(_player.CurrentItem.Duration.Seconds); var totalProgress = Position.TotalMilliseconds / totalDuration.TotalMilliseconds; PlayingChanged?.Invoke(this, new PlayingChangedEventArgs(totalProgress, Position, Duration)); }); }
public void PrepareForUrl(NSUrl url) { AssetUrl = url; CleanPreviousResources(); PlayerItem = new AVPlayerItem(url); PlayerItem.AddObserver(this, StatusKey, NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, StatusContext.Handle); PlayerItem.AddObserver(this, LoadedTimeRangesKey, NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, TimeRangesContext.Handle); PlayerItem.AddObserver(this, PlaybackBufferEmptyKey, NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, PlaybackBufferEmptyContext.Handle); if (Player != null) { Player.Dispose(); } Player = new AVPlayer(PlayerItem); }
partial void Play (NSObject sender) { // An AVPlayerLayer has already been created for this asset; just play it. if (playerLayer != null) { playerLayer.Player.Play (); } else { // Request an AVAsset for the displayed PHAsset and set up a layer for playing it. PHImageManager.DefaultManager.RequestAvAsset (Asset, null, (avAsset, audioMix, info) => { DispatchQueue.MainQueue.DispatchSync (() => { if (playerLayer != null) return; // Create an AVPlayerItem for the AVAsset. var playerItem = new AVPlayerItem (avAsset); playerItem.AudioMix = audioMix; // Create an AVPlayer with the AVPlayerItem. var player = new AVPlayer (playerItem); // Create an AVPlayerLayer with the AVPlayer. var layer = AVPlayerLayer.FromPlayer (player); layer.VideoGravity = AVLayerVideoGravity.ResizeAspect; layer.Frame = View.Layer.Bounds; View.Layer.AddSublayer (layer); player.Play (); // Refer to the player layer so we can remove it later. playerLayer = layer; }); }); } }
private void InitializePlayer() { _player = new AVPlayer(); Player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate { var totalDuration = TimeSpan.FromSeconds(_player.CurrentItem.Duration.Seconds); var totalProgress = Position.TotalMilliseconds/ totalDuration.TotalMilliseconds; PlayingChanged?.Invoke(this, new PlayingChangedEventArgs(totalProgress, Position, Duration)); }); }
private void PlatformInitialize(NSUrl url) { _sound = AVPlayerItem.FromUrl(url); _player = AVPlayer.FromPlayerItem(_sound); playToEndObserver = AVPlayerItem.Notifications.ObserveDidPlayToEndTime(OnFinishedPlaying); }
public override void ViewDidLoad() { base.ViewDidLoad (); this.RecordingStatusLabel.Text = ""; this.LengthOfRecordingLabel.Text = ""; // start recording wireup this.StartRecordingButton.TouchUpInside += (sender, e) => { Console.WriteLine("Begin Recording"); AudioSession.Category = AudioSessionCategory.RecordAudio; AudioSession.SetActive (true); if (!PrepareAudioRecording ()) { RecordingStatusLabel.Text = "Error preparing"; return; } if (!recorder.Record ()) { RecordingStatusLabel.Text = "Error recording"; return; } this.stopwatch = new Stopwatch(); this.stopwatch.Start(); this.LengthOfRecordingLabel.Text = ""; this.RecordingStatusLabel.Text = "Recording"; this.StartRecordingButton.Enabled = false; this.StopRecordingButton.Enabled = true; this.PlayRecordedSoundButton.Enabled = false; }; // stop recording wireup this.StopRecordingButton.TouchUpInside += (sender, e) => { this.recorder.Stop(); this.LengthOfRecordingLabel.Text = string.Format("{0:hh\\:mm\\:ss}", this.stopwatch.Elapsed); this.stopwatch.Stop(); this.RecordingStatusLabel.Text = ""; this.StartRecordingButton.Enabled = true; this.StopRecordingButton.Enabled = false; this.PlayRecordedSoundButton.Enabled = true; }; observer = NSNotificationCenter.DefaultCenter.AddObserver (AVPlayerItem.DidPlayToEndTimeNotification, delegate (NSNotification n) { player.Dispose (); player = null; }); // play recorded sound wireup this.PlayRecordedSoundButton.TouchUpInside += (sender, e) => { try { Console.WriteLine("Playing Back Recording " + this.audioFilePath.ToString()); // The following line prevents the audio from stopping // when the device autolocks. will also make sure that it plays, even // if the device is in mute AudioSession.Category = AudioSessionCategory.MediaPlayback; this.player = new AVPlayer (this.audioFilePath); this.player.Play(); } catch (Exception ex) { Console.WriteLine("There was a problem playing back audio: "); Console.WriteLine(ex.Message); } }; }
public void Open(string videoFileName) { _playerLoaded = false; if (_player != null) { try { _player.Pause(); _player.Dispose(); _player = null; foreach (var subView in View.VideoView.Subviews) { subView.RemoveFromSuperview(); } foreach (var subLayer in View.VideoView.Layer.Sublayers) { subLayer.RemoveFromSuperLayer(); } _playerLayer.Dispose(); _playerItem.Dispose(); _asset.Dispose(); } catch { } } ShowPlayImage(false); _asset = AVAsset.FromUrl(NSUrl.FromFilename(videoFileName)); _playerItem = new AVPlayerItem(_asset); _player = new AVPlayer(_playerItem); _playerLayer = AVPlayerLayer.FromPlayer(_player); _videoView = new NSMyVideoView(new CoreGraphics.CGRect(0, 0, View.VideoView.Frame.Width, View.VideoView.Frame.Width), View.VideoView, _playerLayer); _videoView.WantsLayer = true; View.VideoView.AddSubview(_videoView); View.VideoView.WantsLayer = true; _playerLayer.Frame = View.VideoView.Bounds; View.VideoView.Layer.AddSublayer(_playerLayer); _videoView.ResizeWithCorrectAspectRatio(); _playerLoaded = true; }
void OnDidPlayToEndTime (object sender, NSNotificationEventArgs e) { player.Dispose (); player = null; }
partial void PlayButtonClickHandler (NSObject sender) { if (LivePhotoView.LivePhoto != null) { // We're displaying a live photo, begin playing it. LivePhotoView.StartPlayback (PHLivePhotoViewPlaybackStyle.Full); } else if (playerLayer != null) { // An AVPlayerLayer has already been created for this asset. playerLayer.Player.Play (); } else { // Request an AVAsset for the PHAsset we're displaying. PHImageManager.DefaultManager.RequestAvAsset (Asset, null, (asset, audioMix, info) => DispatchQueue.MainQueue.DispatchAsync (() => { if (playerLayer == null) { CALayer viewLayer = View.Layer; // Create an AVPlayerItem for the AVAsset. var playerItem = new AVPlayerItem (asset); playerItem.AudioMix = audioMix; // Create an AVPlayer with the AVPlayerItem. var player = new AVPlayer (playerItem); // Create an AVPlayerLayer with the AVPlayer. playerLayer = AVPlayerLayer.FromPlayer (player); // Configure the AVPlayerLayer and add it to the view. playerLayer.VideoGravity = AVLayerVideoGravity.ResizeAspect; playerLayer.Frame = new CGRect (0, 0, viewLayer.Bounds.Width, viewLayer.Bounds.Height); viewLayer.AddSublayer (playerLayer); playerLayer.Player.Play (); } })); } }
private void PlaySound(string path) { if (!string.IsNullOrEmpty (path)) { NSUrl soundUrl = NSUrl.FromFilename(path); player = new AVPlayer (soundUrl); player.Play (); } }
public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); if (Player == null) { seekToZeroBeforePlaying = false; Player = new AVPlayer (); Player.AddObserver (this, (NSString)"rate", NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.New, RateObservationContext.Handle); playerView.player = Player; } addTimeObserverToPlayer (); // Build AVComposition and AVVideoComposition objects for playback Editor.BuildCompositionObjects (true); synchronizePlayerWithEditor (); }
public void Play(Uri source) { Debug.WriteLine("Start playing"); AVAsset asset = AVAsset.FromUrl(source); AVPlayerItem playerItem = new AVPlayerItem(asset); avPlayer = new AVPlayer(playerItem); // playerItem.AddObserver(observer: this, // keyPath: new NSString("playbackLikelyToKeepUp"), // options: NSKeyValueObservingOptions.New, // context: itemContext); // playerItem.AddObserver(observer: this, // keyPath: new NSString("status"), // options: NSKeyValueObservingOptions.New, // context: itemContext); // avPlayer.AddObserver(observer: this, // keyPath: new NSString("status"), // options: NSKeyValueObservingOptions.New, // context: playerContext); avPlayer.Play(); }
public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); if (Player == null) { seekToZeroBeforePlaying = false; Player = new AVPlayer (); playerView.Player = Player; compositionDebugView.Player = Player; } AddTimeObserverToPlayer (); Editor.BuildCompositionObjects (true); SynchronizeWithEditor (); // Set our AVPlayer and all composition objects on the AVCompositionDebugView compositionDebugView.Player = Player; compositionDebugView.SynchronizeToCompositoin (Editor.Composition, Editor.VideoComposition, Editor.AudioMix); compositionDebugView.SetNeedsDisplay (); }
void OnPlayRecordedSound (object sender, EventArgs e) { try { Console.WriteLine ("Playing Back Recording {0}", audioFilePath); // The following line prevents the audio from stopping // when the device autolocks. will also make sure that it plays, even // if the device is in mute NSError error = null; AVAudioSession.SharedInstance ().SetCategory (AVAudioSession.CategoryPlayback, out error); if (error != null) throw new Exception (error.DebugDescription); player = new AVPlayer (audioFilePath); player.Play (); } catch (Exception ex) { Console.WriteLine ("There was a problem playing back audio: "); Console.WriteLine (ex.Message); } }
private void InitializePlayer() { _player = new AVPlayer(); _videoLayer = AVPlayerLayer.FromPlayer(_player); var avSession = AVAudioSession.SharedInstance(); // By setting the Audio Session category to AVAudioSessionCategorPlayback, audio will continue to play when the silent switch is enabled, or when the screen is locked. avSession.SetCategory(AVAudioSessionCategory.Playback); NSError activationError = null; avSession.SetActive(true, out activationError); if (activationError != null) Console.WriteLine("Could not activate audio session {0}", activationError.LocalizedDescription); Player.AddPeriodicTimeObserver(new CMTime(1, 4), DispatchQueue.MainQueue, delegate { var totalDuration = TimeSpan.FromSeconds(_player.CurrentItem.Duration.Seconds); var totalProgress = Position.TotalMilliseconds / totalDuration.TotalMilliseconds; PlayingChanged?.Invoke(this, new PlayingChangedEventArgs(totalProgress, Position, Duration)); }); }
public void DisposeVideoPlayer() { if (!_playerLoaded || _player == null) { return; } if (_positionDisplayTimer != null) { _positionDisplayTimer.Stop(); } _player.Pause(); _playerLoaded = false; _asset = null; _playerItem = null; _playerLayer = null; _player = null; }
private void PlaySound(string soundFilePath) { NSUrl soundUrl = NSUrl.FromFilename(soundFilePath); AVPlayer player = new AVPlayer (soundUrl); player.Play (); }
void OnButtonClick(object sender, EventArgs e) { if (!Reachability.IsHostReachable("live2.artoflogic.com")) { Debug.WriteLine("Host unreachable"); return; } if (player?.Rate > 0 && player.Error == null) { // Player is playing. Let's stop it. Debug.WriteLine("OnButtonClick() - stopping player"); player.Pause(); player.Dispose(); playPauseButton.SetTitle("Play", UIControlState.Normal); } else { Debug.WriteLine("OnButtonClick() - starting player"); player = new AVPlayer(source); player.Play(); playPauseButton.SetTitle("Stop", UIControlState.Normal); } }
public override void ViewDidLoad () { base.ViewDidLoad (); string path = NSBundle.MainBundle.PathForResource ("Dramatic2", "m4a"); if (path != null) { memeEffect = AVPlayer.FromUrl (NSUrl.FromFilename (path)); memeEffect.AddObserver (this, (NSString) "rate", (NSKeyValueObservingOptions)0, MemePlaybackContext); } path = NSBundle.MainBundle.PathForResource ("Sosumi", "wav"); if (path != null) beepEffect = AVPlayer.FromUrl (NSUrl.FromFilename (path)); setupAVCapture (); if (MaxZoom == 1f && device != null) { displayErrorOnMainQueue (null, "Device does not support zoom"); slider.Enabled = false; } }