public override void ViewDidLoad() { base.ViewDidLoad (); //largely taken from the xamarin website videoplayer tutorial //build the path to the location where the movie was saved var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var library = System.IO.Path.Combine (documents, "..", "Library"); var urlpath = System.IO.Path.Combine (library, "sweetMovieFilm.mov"); NSUrl url = new NSUrl (urlpath, false); _asset = AVAsset.FromUrl(url); _playerItem = new AVPlayerItem (_asset); _player = new AVPlayer (_playerItem); _playerLayer = AVPlayerLayer.FromPlayer (_player); _playerLayer.Frame = View.Frame; View.Layer.AddSublayer (_playerLayer); //this code makes UI controls sit on top of the movie layer. Allows you to just place the controls in interface builder UIView cameraView = new UIView (); this.View.AddSubview (cameraView); this.View.SendSubviewToBack (cameraView); cameraView.Layer.AddSublayer (_playerLayer); _player.Play (); this.btnDonePlaying.TouchUpInside += stopPlaying; }
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 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); }
private void BtnPlay_TouchUpInside(object sender, EventArgs e) { avAsset = AVAsset.FromUrl(NSUrl.FromFilename("video.mp4")); avPlayerItem = new AVPlayerItem(avAsset); avPlayer = new AVPlayer(avPlayerItem); avPlayerLayer = AVPlayerLayer.FromPlayer(avPlayer); avPlayerLayer.Frame = View.Frame; View.Layer.AddSublayer(avPlayerLayer); avPlayer.Play(); }
private void UpdateSource() { if (Element.Source != null) { AVAsset asset = null; if (Element.Source.Scheme == null) { // file path asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source.OriginalString)); } else if (Element.Source.Scheme == "ms-appx") { // used for a file embedded in the application package asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source.LocalPath.Substring(1))); } else if (Element.Source.Scheme == "ms-appdata") { asset = AVAsset.FromUrl(NSUrl.FromFilename(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Element.Source.LocalPath.Substring(1)))); } else { asset = AVUrlAsset.Create(NSUrl.FromString(Element.Source.ToString()), GetOptionsWithHeaders(Element.HttpHeaders)); } AVPlayerItem item = new AVPlayerItem(asset); if (observer != null) { if (_avPlayerViewController.Player != null && _avPlayerViewController.Player.CurrentItem != null) { _avPlayerViewController.Player.CurrentItem.RemoveObserver(observer, "status"); } observer.Dispose(); observer = null; } observer = (NSObject)item.AddObserver("status", 0, ObserveStatus); if (_avPlayerViewController.Player != null) { _avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(item); } else { _avPlayerViewController.Player = new AVPlayer(item); } if (Element.AutoPlay) { _avPlayerViewController.Player.Play(); Element.CurrentState = MediaElementState.Playing; } } }
protected virtual void InitializeSource() { PlaybackSession.NaturalDuration = TimeSpan.Zero; PlaybackSession.PositionFromPlayer = TimeSpan.Zero; if (Source == null) { return; } try { // Reset player TryDisposePlayer(); InitializePlayer(); PlaybackSession.PlaybackState = MediaPlaybackState.Opening; _player.CurrentItem?.RemoveObserver(this, new NSString("duration"), _player.Handle); _player.CurrentItem?.RemoveObserver(this, new NSString("status"), _player.Handle); _player.CurrentItem?.RemoveObserver(this, new NSString("loadedTimeRanges"), _player.Handle); if (Source is MediaPlaybackList) { var items = ((MediaPlaybackList)Source).Items; foreach (var item in items) { var asset = AVAsset.FromUrl(DecodeUri(item.Source.Uri)); _player.InsertItem(new AVPlayerItem(asset), null); } } else { var nsAsset = AVAsset.FromUrl(DecodeUri(((MediaSource)Source).Uri)); var streamingItem = AVPlayerItem.FromAsset(nsAsset); _player.ReplaceCurrentItemWithPlayerItem(streamingItem); } _player.CurrentItem.AddObserver(this, new NSString("duration"), NSKeyValueObservingOptions.Initial, _player.Handle); _player.CurrentItem.AddObserver(this, new NSString("status"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, _player.Handle); _player.CurrentItem.AddObserver(this, new NSString("loadedTimeRanges"), NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, _player.Handle); _player.CurrentItem.SeekingWaitsForVideoCompositionRendering = true; // Adapt pitch to prevent "metallic echo" when changing playback rate _player.CurrentItem.AudioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.TimeDomain; MediaOpened?.Invoke(this, null); } catch (Exception ex) { OnMediaFailed(ex); } }
public AVReaderWriter (AVAsset asset, IVideoTransformer transformer) { if (asset == null) throw new ArgumentNullException ("asset"); if (transformer == null) throw new ArgumentNullException ("transformer"); this.asset = asset; this.transformer = transformer; cancellationTokenSrc = new CancellationTokenSource (); }
void SetSource() { _logger.Log("SetSource invoked."); AVAsset asset = null; if (Element.Source is UriVideoSource) { string uri = (Element.Source as UriVideoSource).Uri; if (!String.IsNullOrWhiteSpace(uri)) { asset = AVAsset.FromUrl(new NSUrl(uri)); } } else if (Element.Source is FileVideoSource) { string uri = (Element.Source as FileVideoSource).File; if (!String.IsNullOrWhiteSpace(uri)) { asset = AVAsset.FromUrl(new NSUrl(uri)); } } else if (Element.Source is ResourceVideoSource) { string path = (Element.Source as ResourceVideoSource).Path; if (!String.IsNullOrWhiteSpace(path)) { string directory = Path.GetDirectoryName(path); string filename = Path.GetFileNameWithoutExtension(path); string extension = Path.GetExtension(path).Substring(1); NSUrl url = NSBundle.MainBundle.GetUrlForResource(filename, extension, directory); asset = AVAsset.FromUrl(url); } } if (asset != null) { playerItem = new AVPlayerItem(asset); } else { playerItem = null; } player.ReplaceCurrentItemWithPlayerItem(playerItem); if (playerItem != null && Element.AutoPlay) { player.Play(); } }
public void DecompressionSessionCreateTest() { TestRuntime.AssertSystemVersion(PlatformName.iOS, 8, 0, throwIfOtherPlatform: false); TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 8, throwIfOtherPlatform: false); TestRuntime.AssertSystemVersion(PlatformName.TvOS, 10, 2, throwIfOtherPlatform: false); using (var asset = AVAsset.FromUrl(NSBundle.MainBundle.GetUrlForResource("xamvideotest", "mp4"))) using (var session = CreateSession(asset)){ Assert.IsNotNull(session, "Session should not be null"); } }
public byte[] GenerateThumbImage(string url, long second) { AVAssetImageGenerator imageGenerator = new AVAssetImageGenerator(AVAsset.FromUrl((new Foundation.NSUrl(url)))); imageGenerator.AppliesPreferredTrackTransform = true; CMTime actualTime; NSError error; CGImage cgImage = imageGenerator.CopyCGImageAtTime(new CMTime(second, 1000000), out actualTime, out error); return(new UIImage(cgImage).AsPNG().ToArray()); }
void ReadSampleBuffers(AVAsset asset) { NSError error; assetReader = AVAssetReader.FromAsset(asset, out error); if (error != null) { Console.WriteLine("Error creating Asset Reader: {0}", error.Description); } AVAssetTrack[] videoTracks = asset.TracksWithMediaType(AVMediaType.Video); AVAssetTrack videoTrack = videoTracks [0]; CreateDecompressionSession(videoTrack); var videoTrackOutput = AVAssetReaderTrackOutput.Create(videoTrack, (AVVideoSettingsUncompressed)null); if (assetReader.CanAddOutput(videoTrackOutput)) { assetReader.AddOutput(videoTrackOutput); } if (!assetReader.StartReading()) { return; } while (assetReader.Status == AVAssetReaderStatus.Reading) { CMSampleBuffer sampleBuffer = videoTrackOutput.CopyNextSampleBuffer(); if (sampleBuffer != null) { VTDecodeFrameFlags flags = VTDecodeFrameFlags.EnableAsynchronousDecompression; VTDecodeInfoFlags flagOut; decompressionSession.DecodeFrame(sampleBuffer, flags, IntPtr.Zero, out flagOut); sampleBuffer.Dispose(); if (presentationTimes.Count >= 5) { bufferSemaphore.Wait(); } } else if (assetReader.Status == AVAssetReaderStatus.Failed) { Console.WriteLine("Asset Reader failed with error: {0}", assetReader.Error.Description); } else if (assetReader.Status == AVAssetReaderStatus.Completed) { Console.WriteLine("Reached the end of the video."); ChangeStatus(); ReadSampleBuffers(asset); } } }
public void Defaults() { using (NSUrl video_url = NSUrl.FromFilename(video_asset_path)) using (AVAsset video_asset = AVAsset.FromUrl(video_url)) using (AVAssetImageGenerator aig = new AVAssetImageGenerator(video_asset)) { Assert.Null(aig.ApertureMode, "ApertureMode"); Assert.False(aig.AppliesPreferredTrackTransform, "AppliesPreferredTrackTransform"); Assert.That(aig.MaximumSize, Is.EqualTo(CGSize.Empty), "MaximumSize"); Assert.True(aig.RequestedTimeToleranceAfter.IsPositiveInfinity, "RequestedTimeToleranceAfter"); Assert.True(aig.RequestedTimeToleranceBefore.IsPositiveInfinity, "RequestedTimeToleranceBefore"); } }
public ImageSource GenerateThumbImage(string url, long usecond) { AVAssetImageGenerator imageGenerator = new AVAssetImageGenerator(AVAsset.FromUrl((new Foundation.NSUrl(url)))); imageGenerator.AppliesPreferredTrackTransform = true; CMTime actualTime; NSError error; CGImage cgImage = imageGenerator.CopyCGImageAtTime(new CMTime(usecond, 1000000), out actualTime, out error); return(ImageSource.FromStream(() => new UIImage(cgImage).AsPNG().AsStream())); //ImageSource.FromStream(() => new UIImage(cgImage).AsPNG().AsStream()); }
public override async void WindowControllerDidLoadNib (NSWindowController windowController) { base.WindowControllerDidLoadNib (windowController); // Add code to here after the controller has loaded the document window var filename = Path.Combine (NSBundle.MainBundle.BundlePath, "sample_iTunes.mov"); NSUrl url = NSUrl.FromFilename ("/Users/kichang/Downloads/sample_iTunes.mov"); asset = AVAsset.FromUrl (url); string[] keys = { "playable", "hasProtectedContent", "tracks", "duration" }; Task task = asset.LoadValuesTaskAsync (keys); await task; NSError assetError; if (asset.StatusOfValue ("playable", out assetError) == AVKeyValueStatus.Failed) { return; } if (asset.Playable) { float height = asset.Tracks [0].NaturalSize.Height; float width = asset.Tracks [0].NaturalSize.Width; playerItem = new AVPlayerItem (asset); player = new AVPlayer (); playerLayer = AVPlayerLayer.FromPlayer (player); playerView.WantsLayer = true; playerView.Layer.BackgroundColor = new CGColor (1, 1, 1, 1); playerLayer.Frame = new RectangleF (0, 0, width, height); playerView.Frame = playerLayer.Frame; playerView.Layer.AddSublayer (playerLayer); player.ReplaceCurrentItemWithPlayerItem (playerItem); player.Play (); } }
public void DecompressionSessionCreateTest() { if (!TestRuntime.CheckSystemAndSDKVersion(8, 0)) { Assert.Ignore("Ignoring VideoToolbox tests: Requires iOS8+"); } using (var asset = AVAsset.FromUrl(NSBundle.MainBundle.GetUrlForResource("xamvideotest", "mp4"))) using (var session = CreateSession(asset)){ Assert.IsNotNull(session, "Session should not be null"); } }
protected override void OnElementChanged(ElementChangedEventArgs <View> e) { base.OnElementChanged(e); if (e.NewElement is VideoPlayer parentPlayer) { _player = new AVPlayer(); _playerLayer = AVPlayerLayer.FromPlayer(_player); _contentType = parentPlayer.ContentType; var url = _contentType == Constants.ContentType.Remote ? new NSUrl(parentPlayer.Source) : new NSUrl(parentPlayer.Source, false); _asset = AVAsset.FromUrl(url); _playerItem = new AVPlayerItem(_asset); _player.ReplaceCurrentItemWithPlayerItem(_playerItem); videoLengthThread = new Thread(new ThreadStart(() => { _totalLength = _player.CurrentItem.Asset.Duration.Seconds; InvokeOnMainThread(() => { parentPlayer.SoundLength?.Invoke(this, _totalLength); }); })); videoLengthThread.Start(); parentPlayer.Play += (sender, innere) => { if (videoLengthThread.IsAlive) { videoLengthThread.Abort(); _totalLength = _player.CurrentItem.Asset.Duration.Seconds; parentPlayer.SoundLength?.Invoke(this, _totalLength); } StartTimeObserver(parentPlayer); _player.Play(); }; parentPlayer.Pause += (sender, innere) => { _player.Pause(); }; parentPlayer.Stop += (sender, innere) => { EndTimeObserver(); _player.Stop(); }; parentPlayer.GoToTime += (sender, sec) => { _player.SeekAsync(CoreMedia.CMTime.FromSeconds(sec, Constants.NSEC_PER_SEC)); }; } }
VTDecompressionSession CreateSession(AVAsset asset) { var videoTracks = asset.TracksWithMediaType(AVMediaType.Video); var track = videoTracks[0]; var formatDescriptor = track.FormatDescriptions[0] as CMVideoFormatDescription; var session = VTDecompressionSession.Create( (sourceFrame, status, flags, buffer, presentationTimeStamp, presentationDuration) => {}, formatDescriptor); return(session); }
public void DecompressionSessionGetSupportedPropertiesTest() { TestRuntime.AssertSystemVersion(PlatformName.iOS, 8, 0, throwIfOtherPlatform: false); TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 8, throwIfOtherPlatform: false); TestRuntime.AssertSystemVersion(PlatformName.TvOS, 10, 2, throwIfOtherPlatform: false); using (var asset = AVAsset.FromUrl(NSBundle.MainBundle.GetUrlForResource("xamvideotest", "mp4"))) using (var session = CreateSession(asset)) { var supportedProps = session.GetSupportedProperties(); Assert.NotNull(supportedProps, "GetSupportedProperties"); Assert.That(supportedProps.Count, Is.GreaterThan(0), "GetSupportedProperties should be more than zero"); } }
private void Play(int index) { Stop(); Prepare(); var songToPlay = _items.ElementAt(index); UpdateNowPlaying(songToPlay); var avasset = AVAsset.FromUrl(NSUrl.FromString(songToPlay.SongUri.OriginalString)); var avplayerItem = new AVPlayerItem(avasset); _avPlayer = new AVPlayer(avplayerItem); _avPlayer.Play(); }
UIImage ImageFor(AVAsset avAsset, double time) { AVAssetImageGenerator imageGenerator = AVAssetImageGenerator.FromAsset(avAsset); imageGenerator.AppliesPreferredTrackTransform = true; CMTime actualTime; NSError error = null; var requestedTime = new CMTime((long)time, 100); using (CGImage posterImage = imageGenerator.CopyCGImageAtTime(requestedTime, out actualTime, out error)) return(UIImage.FromImage(posterImage)); }
public async Task Play(IMediaFile mediaFile = null) { if (mediaFile != null) { nsUrl = new NSUrl(mediaFile.Url); } if (Status == MediaPlayerStatus.Paused) { Status = MediaPlayerStatus.Playing; //We are simply paused so just start again Player.Play(); return; } try { // Start off with the status LOADING. Status = MediaPlayerStatus.Buffering; var nsAsset = AVAsset.FromUrl(nsUrl); var streamingItem = AVPlayerItem.FromAsset(nsAsset); Player.CurrentItem?.RemoveObserver(this, new NSString("status")); Player.ReplaceCurrentItemWithPlayerItem(streamingItem); streamingItem.AddObserver(this, new NSString("status"), NSKeyValueObservingOptions.New, Player.Handle); streamingItem.AddObserver(this, new NSString("loadedTimeRanges"), NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, Player.Handle); Player.CurrentItem.SeekingWaitsForVideoCompositionRendering = true; Player.CurrentItem.AddObserver(this, (NSString)"status", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle); NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, notification => MediaFinished?.Invoke(this, new MediaFinishedEventArgs(mediaFile)), Player.CurrentItem); Player.Play(); } catch (Exception ex) { OnMediaFailed(); Status = MediaPlayerStatus.Stopped; //unable to start playback log error Console.WriteLine("Unable to start playback: " + ex); } await Task.CompletedTask; }
public bool CanReadRecordingMetadata(string localFilePath) { try { using (AVAsset asset = AVAsset.FromUrl(NSUrl.FromFilename(localFilePath))) return(isRecording(asset)); } catch (Exception ex) { Logger.Log("ERROR: LocalLibrary.CanReadRecordingMetadata: " + ex); } return(false); }
private Task <AVAsset> LoadAsset(AtomVideoSource source) { if (source.Url != null) { return(Task.FromResult(AVAsset.FromUrl(new NSUrl(source.Url)))); } if (source.FilePath != null) { return(Task.FromResult(AVAsset.FromUrl(new NSUrl(source.FilePath, false)))); } throw new NotImplementedException(); }
private void SetSource() { try { if (string.IsNullOrWhiteSpace(Element.Source)) { return; } _prepared = false; if (_player != null) { _player.Dispose(); _player = null; } AVPlayerItem playerItem = null; if (Element.Source.StartsWith("http://") || Element.Source.StartsWith("https://")) { playerItem = new AVPlayerItem(AVAsset.FromUrl(NSUrl.FromString(Element.Source))); } else { playerItem = new AVPlayerItem(NSUrl.FromFilename(Element.Source)); } NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, DidVideoFinishPlaying, playerItem); NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.ItemFailedToPlayToEndTimeNotification, DidVideoErrorOcurred, playerItem); NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.NewErrorLogEntryNotification, DidVideoErrorOcurred, playerItem); //NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.PlaybackStalledNotification, DidVideoPrepared, playerItem); _player = new AVPlayer(playerItem); _player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None; _playerController.Player = _player; _prepared = true; if (Element.AutoPlay) { _player.Play(); } if (_player.Error != null) { Element.OnError(_playerController?.Player?.Error?.LocalizedDescription); } } catch (Exception e) { Element.OnError(e.Message); } }
private async Task<MediaFile> GetMovieMediaFile(NSDictionary info) { var url = (NSUrl)info[UIImagePickerController.MediaURL]; var path = GetOutputPath(MediaImplementation.TypeMovie, options.Directory ?? ((IsCaptured) ? string.Empty : "temp"), options.Name ?? Path.GetFileName(url.Path)); try { File.Move(url.Path, path); } catch (Exception ex) { Console.WriteLine($"Unable to move file, trying to copy. {ex.Message}"); try { File.Copy(url.Path, path); File.Delete(url.Path); } catch (Exception) { Console.WriteLine($"Unable to copy/delete file, will be left around :( {ex.Message}"); } } string aPath = path; if (source != UIImagePickerControllerSourceType.Camera) { //try to get the album path's url var url2 = (NSUrl)info[UIImagePickerController.ReferenceUrl]; aPath = url2?.AbsoluteString; } else { if (options.SaveToAlbum) { PhotoLibraryAccess.SaveVideoToGalery(url, path, options.Directory); } } var asset = AVAsset.FromUrl(new NSUrl($"file://{path}")); var duration = asset.Duration.Seconds; return new MediaFile(path, () => File.OpenRead(path), albumPath: aPath) { Type = MediaType.Video, Duration = duration, }; }
protected virtual void InitializeSource() { PlaybackSession.NaturalDuration = TimeSpan.Zero; PlaybackSession.PositionFromPlayer = TimeSpan.Zero; if (Source == null) { return; } try { // Reset player TryDisposePlayer(); InitializePlayer(); PlaybackSession.PlaybackState = MediaPlaybackState.Opening; var nsAsset = AVAsset.FromUrl(DecodeUri(((MediaSource)Source).Uri)); var streamingItem = AVPlayerItem.FromAsset(nsAsset); _player.CurrentItem?.RemoveObserver(this, new NSString("duration"), _player.Handle); _player.CurrentItem?.RemoveObserver(this, new NSString("status"), _player.Handle); _player.CurrentItem?.RemoveObserver(this, new NSString("loadedTimeRanges"), _player.Handle); _player.ReplaceCurrentItemWithPlayerItem(streamingItem); _player.CurrentItem.AddObserver(this, new NSString("duration"), NSKeyValueObservingOptions.Initial, _player.Handle); _player.CurrentItem.AddObserver(this, new NSString("status"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, _player.Handle); _player.CurrentItem.AddObserver(this, new NSString("loadedTimeRanges"), NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, _player.Handle); _player.CurrentItem.SeekingWaitsForVideoCompositionRendering = true; // Adapt pitch to prevent "metallic echo" when changing playback rate _player.CurrentItem.AudioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.TimeDomain; // Disable subtitles if any var mediaSelectionGroup = _player.CurrentItem.Asset.MediaSelectionGroupForMediaCharacteristic(AVMediaCharacteristic.Legible); if (mediaSelectionGroup != null) { _player.CurrentItem.SelectMediaOption(null, mediaSelectionGroup); } MediaOpened?.Invoke(this, null); } catch (Exception ex) { OnMediaFailed(ex); } }
void InitializePlayer() { ShouldDisposeView = true; if (DownloadedFile != null) { PlayerItem = new AVPlayerItem(DownloadedFile); } else if (Path.IsUrl()) { PlayerItem = new AVPlayerItem(new NSUrl(Path)); } else { PlayerItem = new AVPlayerItem(AVAsset.FromUrl(NSUrl.FromString("file://" + IO.File(Path).FullName))); } Player = new AVPlayer(PlayerItem) { Volume = 1.0f }; DidPlayToEndTimeObservation = AVPlayerItem.Notifications.ObserveDidPlayToEndTime(PlayerItem, (_, _) => { Thread.UI.Post(() => Dispose()); }); StatusObservation = PlayerItem.AddObserver(nameof(AVPlayerItem.Status), 0, _ => { if (PlayerItem?.Status == AVPlayerItemStatus.ReadyToPlay) { try { Audio.ConfigureAudio(AVAudioSessionCategory.Playback); } catch { } Player?.Play(); return; } if (PlayerItem?.Status == AVPlayerItemStatus.Failed) { Log.For(this).Error($"Failed to play {Path}"); } else { Log.For(this).Error($"An error occured during playing {Path}"); } RetryToDownloadTrack(); }); }
public void DecompressionSessionGetSupportedPropertiesTest() { if (!TestRuntime.CheckSystemAndSDKVersion(8, 0)) { Assert.Ignore("Ignoring VideoToolbox tests: Requires iOS8+"); } using (var asset = AVAsset.FromUrl(NSBundle.MainBundle.GetUrlForResource("xamvideotest", "mp4"))) using (var session = CreateSession(asset)) { var supportedProps = session.GetSupportedProperties(); Assert.NotNull(supportedProps, "GetSupportedProperties"); Assert.That(supportedProps.Count > 0, "GetSupportedProperties should be more than zero"); } }
public Orientation GetVideoOrientation(string filePath) { var url = NSUrl.CreateFileUrl(filePath, false, null); var asset = AVAsset.FromUrl(url); var tracks = asset.TracksWithMediaType(AVMediaType.Video); if (tracks.Length == 0) { return(Orientation.Unknown); } var track = tracks[0]; return(GetVideoOrientation(track.PreferredTransform)); }
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 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 (); }
protected override void OnElementChanged(ElementChangedEventArgs <View> e) { base.OnElementChanged(e); _asset = AVAsset.FromUrl(NSUrl.FromFilename("intro.mp4")); _playerItem = new AVPlayerItem(_asset); _player = new AVPlayer(_playerItem); _player.ActionAtItemEnd = AVPlayerActionAtItemEnd.None; _playerLayer = AVPlayerLayer.FromPlayer(_player); videoEndNotificationToken = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, VideoDidFinishPlaying, _playerItem); _player.Play(); }
public AVReaderWriter(AVAsset asset, IVideoTransformer transformer) { if (asset == null) { throw new ArgumentNullException("asset"); } if (transformer == null) { throw new ArgumentNullException("transformer"); } this.asset = asset; this.transformer = transformer; cancellationTokenSrc = new CancellationTokenSource(); }
public void CopyCGImageAtTime_Invalid() { // Mov file is not supported by CopCGImageAtTime so we can test out error param using (NSUrl video_url = NSUrl.FromFilename(does_not_exists_asset_path)) using (AVAsset video_asset = AVAsset.FromUrl(video_url)) using (AVAssetImageGenerator aig = new AVAssetImageGenerator(video_asset)) { // signature errors see https://bugzilla.xamarin.com/show_bug.cgi?id=5218 CMTime actual; NSError error; var img = aig.CopyCGImageAtTime(CMTime.Zero, out actual, out error); Assert.Null(img, "missing"); Assert.True(actual.IsInvalid, "actual"); Assert.NotNull(error, "error"); } }
public void LoadAsync(string source) { AVAsset asset; if (string.IsNullOrWhiteSpace(source)) { return; } _prepared = false; if (audioPlayer != null) { audioPlayer.Dispose(); audioPlayer = null; } _prepared = false; _timer = new System.Timers.Timer(1000) { AutoReset = true }; if (source.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase) || source.StartsWith("https://", StringComparison.CurrentCultureIgnoreCase)) { asset = AVAsset.FromUrl(NSUrl.FromString(source)); } else { asset = AVAsset.FromUrl(NSUrl.FromFilename(source)); } var playerItem = new AVPlayerItem(asset); audioPlayer = new AVPlayer(playerItem); NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, DidVideoFinishPlaying, playerItem); //NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.ItemFailedToPlayToEndTimeNotification, DidVideoErrorOcurred, playerItem); //NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.NewErrorLogEntryNotification, DidVideoErrorOcurred, playerItem); _timer.Elapsed += (s, e) => { if (SeekPositionChanged != null) { SeekPositionChanged.Invoke(this, CurrentPosition); } }; _prepared = true; SetTotalDuration(); }
public async Task <IMediaFile> ExtractMediaInfo(IMediaFile mediaFile) { try { if (mediaFile.ExtractMetadata) { var assetsToLoad = new List <string> { AVMetadata.CommonKeyArtist, AVMetadata.CommonKeyTitle, AVMetadata.CommonKeyArtwork }; var url = MediaFileUrlHelper.GetUrlFor(mediaFile); // Default title to filename mediaFile.Metadata.Title = url.LastPathComponent; var asset = AVAsset.FromUrl(url); await asset.LoadValuesTaskAsync(assetsToLoad.ToArray()); foreach (var avMetadataItem in asset.CommonMetadata) { if (avMetadataItem.CommonKey == AVMetadata.CommonKeyArtist) { mediaFile.Metadata.Artist = ((NSString)avMetadataItem.Value).ToString(); } else if (avMetadataItem.CommonKey == AVMetadata.CommonKeyTitle) { mediaFile.Metadata.Title = ((NSString)avMetadataItem.Value).ToString(); } else if (avMetadataItem.CommonKey == AVMetadata.CommonKeyArtwork) { #if __IOS__ || __TVOS__ var image = UIImage.LoadFromData(avMetadataItem.DataValue); mediaFile.Metadata.AlbumArt = image; #endif } } mediaFile.MetadataExtracted = true; } return(mediaFile); } catch (Exception) { return(mediaFile); } }
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; }
private void initializeVideo() { var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var library = System.IO.Path.Combine (documents, "..", "Library"); var urlpath = System.IO.Path.Combine (library, "sweetMovieFilm.mov"); url = new NSUrl (urlpath, false); _asset = AVAsset.FromUrl(url); _playerItem = new AVPlayerItem (_asset); _player = new AVPlayer (_playerItem); _notificationHandle = NSNotificationCenter.DefaultCenter.AddObserver (AVPlayerItem.DidPlayToEndTimeNotification, VideoDonePlaying); _playerLayer = AVPlayerLayer.FromPlayer (_player); _playerLayer.Frame = View.Frame; }
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; }
public AVReaderWriter (AVAsset asset) { _asset = asset; _cancellationTokenSrc = new CancellationTokenSource (); }
void ReadSampleBuffers(AVAsset asset) { NSError error; assetReader = AVAssetReader.FromAsset (asset, out error); if (error != null) Console.WriteLine ("Error creating Asset Reader: {0}", error.Description); AVAssetTrack[] videoTracks = asset.TracksWithMediaType (AVMediaType.Video); AVAssetTrack videoTrack = videoTracks [0]; CreateDecompressionSession (videoTrack); var videoTrackOutput = AVAssetReaderTrackOutput.Create (videoTrack, (AVVideoSettingsUncompressed)null); if (assetReader.CanAddOutput (videoTrackOutput)) assetReader.AddOutput (videoTrackOutput); if (!assetReader.StartReading ()) return; while (assetReader.Status == AVAssetReaderStatus.Reading) { CMSampleBuffer sampleBuffer = videoTrackOutput.CopyNextSampleBuffer (); if (sampleBuffer != null) { VTDecodeFrameFlags flags = VTDecodeFrameFlags.EnableAsynchronousDecompression; VTDecodeInfoFlags flagOut; decompressionSession.DecodeFrame (sampleBuffer, flags, IntPtr.Zero, out flagOut); sampleBuffer.Dispose (); if (presentationTimes.Count >= 5) bufferSemaphore.Wait (); } else if (assetReader.Status == AVAssetReaderStatus.Failed) { Console.WriteLine ("Asset Reader failed with error: {0}", assetReader.Error.Description); } else if (assetReader.Status == AVAssetReaderStatus.Completed) { Console.WriteLine("Reached the end of the video."); ChangeStatus (); ReadSampleBuffers (asset); } } }
void loadAsset(AVAsset asset, string[] assetKeysToLoad, DispatchGroup dispatchGroup) { dispatchGroup.Enter (); asset.LoadValuesAsynchronously (assetKeysToLoad, () => { foreach(var key in assetKeysToLoad) { NSError error; if(asset.StatusOfValue(key, out error) == AVKeyValueStatus.Failed) { Console.Error.WriteLine("Key value loading failed for key" + key + " with error: "+ error.ToString()); dispatchGroup.Leave(); } } if(!asset.Composable) { Console.Error.WriteLine("Asset is not composable"); dispatchGroup.Leave(); } Clips.Add(asset); ClipTimeRanges.Add(NSValue.FromCMTimeRange(new CMTimeRange(){ Start = CMTime.FromSeconds(0, 1), Duration = CMTime.FromSeconds(5,1) })); dispatchGroup.Leave(); }); }
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; }
public override void ViewDidLoad() { base.ViewDidLoad(); if (((MissionViewModel)ViewModel).Mission.LiveStream) { chatView.Hidden = false; messageField.Hidden = false; sendButton.Hidden = false; firstTitle.Hidden = true; secondTitle.Hidden = true; imageView.Hidden = true; var streamingUri = ((MissionViewModel)ViewModel).LiveStreamViewModel.LiveStreamUrl; _asset = AVAsset.FromUrl(NSUrl.FromString(streamingUri)); _playerItem = new AVPlayerItem(_asset); _player = new AVPlayer(_playerItem); _playerLayer = AVPlayerLayer.FromPlayer(_player); _playerLayer.Frame = new RectangleF(21, 88, 602, 311); View.Layer.AddSublayer(_playerLayer); _player.Play(); ((MissionViewModel)ViewModel).LiveStreamViewModel.UserName = "******"; chatView.Text = ""; var previousText = string.Empty; SunnySocket.MessageReceivedAsyncCallback = (string name, string message) => InvokeOnMainThread(() => { if (message != previousText) { chatView.Text = name + " - " + message + "\n" + chatView.Text; chatView.Font = UIFont.FromName("HelveticaNeue-Bold", 15); chatView.TextColor = UIColor.FromRGBA(0.027f, 0.102f, 0.389f, 1.000f); previousText = message; } }); messageField.ShouldReturn += (x) => { ((MissionViewModel)ViewModel).LiveStreamViewModel.SendMessageCommand.Execute(null); return true; }; var set = this.CreateBindingSet<MissionView, MissionViewModel>(); set.Bind(title).To(vm => vm.Mission.Name); set.Bind(messageField).To(vm => vm.LiveStreamViewModel.Message); set.Bind(backButton).To("GoBackCommand"); set.Bind(sendButton).To("LiveStreamViewModel.SendMessageCommand"); set.Apply(); messageField.BecomeFirstResponder(); } else { chatView.Hidden = true; messageField.Hidden = true; sendButton.Hidden = true; var imageBorder = new UIButton(UIButtonType.System); imageBorder.Frame = new RectangleF(imageView.Frame.X - 1, imageView.Frame.Y - 1, imageView.Frame.Width + 2, imageView.Frame.Height + 2); imageBorder.BackgroundColor = UIColor.Clear; imageBorder.Layer.BorderColor = UIColor.FromRGBA(0.631f, 0.816f, 0.922f, 1.000f).CGColor; imageBorder.Layer.CornerRadius = 4; imageBorder.Layer.BorderWidth = 1; View.AddSubview(imageBorder); var webview = new UIWebView(); webview.Frame = new RectangleF(450, 87, 554, 681); var webviewBorder = new UIButton(UIButtonType.System); webviewBorder.Frame = new RectangleF(webview.Frame.X - 1, webview.Frame.Y - 1, webview.Frame.Width + 2, webview.Frame.Height + 2); webviewBorder.BackgroundColor = UIColor.Clear; webviewBorder.Layer.BorderColor = UIColor.FromRGBA(0.631f, 0.816f, 0.922f, 1.000f).CGColor; webviewBorder.Layer.CornerRadius = 4; webviewBorder.Layer.BorderWidth = 1; View.AddSubview(webviewBorder); View.AddSubview(webview); var newsButton = new UIButton(UIButtonType.System); newsButton.Frame = new RectangleF(21, 485, 360, 60); newsButton.BackgroundColor = UIColor.Clear; newsButton.Layer.BorderColor = UIColor.FromRGBA(0.631f, 0.816f, 0.922f, 1.000f).CGColor; newsButton.Layer.CornerRadius = 4; newsButton.Layer.BorderWidth = 1; View.AddSubview(newsButton); var notifyButton = new UIButton(UIButtonType.System); notifyButton.Frame = new RectangleF(21, 605, 360, 60); notifyButton.BackgroundColor = UIColor.Clear; notifyButton.Layer.BorderColor = UIColor.FromRGBA(0.631f, 0.816f, 0.922f, 1.000f).CGColor; notifyButton.Layer.CornerRadius = 4; notifyButton.Layer.BorderWidth = 1; View.AddSubview(notifyButton); notifyButton.TouchUpInside += (sender, e) => { notifyButton.Enabled = false; new UIAlertView("Thank you", "You'll receive a notification when we go fly fly (or boom boom)", null, "Ok").Show(); }; var imageViewLoader = new MvxImageViewLoader(() => this.imageView); var set = this.CreateBindingSet<MissionView, MissionViewModel>(); set.Bind(imageViewLoader).To(vm => vm.Mission.ImageUri); set.Bind(title).To(vm => vm.Mission.Name); set.Bind(newsButton).To("ShowMissionNewsOverviewCommand"); set.Bind(notifyButton).To("InitPushCommand"); set.Bind(backButton).To("GoBackCommand"); set.Apply(); var html = ((MissionViewModel)ViewModel).Mission.Text; webview.LoadHtmlString(html, null); webview.ShouldStartLoad += shouldStartLoad; } }
UIImage ImageFor(AVAsset avAsset, double time) { AVAssetImageGenerator imageGenerator = AVAssetImageGenerator.FromAsset (avAsset); imageGenerator.AppliesPreferredTrackTransform = true; CMTime actualTime; NSError error = null; var requestedTime = new CMTime ((long)time, 100); using (CGImage posterImage = imageGenerator.CopyCGImageAtTime (requestedTime, out actualTime, out error)) return UIImage.FromImage (posterImage); }