void UpdateSource()
        {
            if (Element.Source != null)
            {
                AVAsset asset = null;

                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")
                {
                    string filePath = ResolveMsAppDataUri(Element.Source);

                    if (string.IsNullOrEmpty(filePath))
                    {
                        throw new ArgumentException("Invalid Uri", "Source");
                    }

                    asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath));
                }
                else
                {
                    asset = AVUrlAsset.Create(NSUrl.FromString(Element.Source.AbsoluteUri), GetOptionsWithHeaders(Element.HttpHeaders));
                }


                AVPlayerItem item = new AVPlayerItem(asset);
                RemoveStatusObserver();

                _statusObserver = (NSObject)item.AddObserver("status", NSKeyValueObservingOptions.New, ObserveStatus);


                if (Control.Player != null)
                {
                    Control.Player.ReplaceCurrentItemWithPlayerItem(item);
                    Control.Player.Volume = (float)Element.Volume;
                }
                else
                {
                    Control.Player        = new AVPlayer(item);
                    _rateObserver         = (NSObject)Control.Player.AddObserver("rate", NSKeyValueObservingOptions.New, ObserveRate);
                    Control.Player.Volume = (float)Element.Volume;
                }

                if (Element.AutoPlay)
                {
                    Play();
                }
            }
            else
            {
                if (Element.CurrentState == MediaElementState.Playing || Element.CurrentState == MediaElementState.Buffering)
                {
                    Control.Player.Pause();
                    Controller.CurrentState = MediaElementState.Stopped;
                }
            }
        }
예제 #2
0
 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();
     };
 }
예제 #3
0
        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();
        }
예제 #4
0
        void SetSource()
        {
            AVAsset asset = null;

            string uri = Element.Source;

            if (!String.IsNullOrWhiteSpace(uri))
            {
                asset = AVAsset.FromUrl(new NSUrl(uri));
            }

            if (asset != null)
            {
                playerItem = new AVPlayerItem(asset);
            }
            else
            {
                playerItem = null;
            }

            player.ReplaceCurrentItemWithPlayerItem(playerItem);

            if (playerItem != null && Element.AutoPlay)
            {
                player.Play();
            }
        }
        public Task <bool> CompressVideo(string inputPath, string outputPath)
        {
            var      task          = new TaskCompletionSource <bool>();
            NSString urlString     = new NSString(inputPath);
            NSUrl    myFileUrl     = new NSUrl(urlString);
            var      export        = new AVAssetExportSession(AVAsset.FromUrl(myFileUrl), AVAssetExportSession.PresetMediumQuality);
            string   videoFilename = outputPath;

            export.OutputUrl      = NSUrl.FromFilename(videoFilename);
            export.OutputFileType = AVFileType.Mpeg4;
            export.ShouldOptimizeForNetworkUse = true;

            export.ExportAsynchronously(() =>
            {
                if (export.Status == AVAssetExportSessionStatus.Completed)
                {
                    var videoData = NSData.FromUrl(NSUrl.FromString(export.OutputUrl.ToString()));
                    NSError err   = null;
                    if (videoData.Save(videoFilename, false, out err))
                    {
                        task.SetResult(true);
                    }
                    else
                    {
                        task.SetResult(true);
                    }
                }
                else
                {
                    task.SetResult(false);
                }
            });

            return(task.Task);
        }
예제 #6
0
        private void syncedChanged()
        {
            if (media == null || media.URL == null)
            {
                return;
            }
            if (media.URL.Substring(media.URL.Length - 3, 3) == "png")
            {
                using (Stream stream = AppDelegate.MomentsManager.FileSystem.getFileStream(media.URL)) {
                    NSData data = NSData.FromStream(stream);
                    this.imageView.Image = UIImage.LoadFromData(data);
                    AppDelegate.MomentsManager.FileSystem.CloseFileStream(stream);
                }
            }
            else
            {
                var nsurl = NSUrl.FromFilename((Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/" + media.URL));

                AVAsset asset = AVAsset.FromUrl(nsurl);
                AVAssetImageGenerator generator = new AVAssetImageGenerator(asset);
                generator.AppliesPreferredTrackTransform = true;
                NSError err           = null;
                CMTime  outTime       = new CMTime();
                CMTime  requestedTime = new CMTime(2, 1);                  // To create thumbnail image
                using (var imgRef = generator.CopyCGImageAtTime(requestedTime, out outTime, out err)){
                    this.imageView.Image = UIImage.FromImage(imgRef);
                }
            }
        }
        public OperationResult <double> GetVideoDuration(string filePath)
        {
            var url   = NSUrl.CreateFileUrl(filePath, false, null);
            var asset = AVAsset.FromUrl(url);

            return(OperationResult <double> .AsSuccess(asset.Duration.Seconds));
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            bool IsFirstLogin = NSUserDefaults.StandardUserDefaults.BoolForKey("SmallVidIntro");


            if (IsFirstLogin)
            {
                avasset = AVAsset.FromUrl(NSUrl.FromFilename("an1.mp4"));
            }
            else
            {
                avasset = AVAsset.FromUrl(NSUrl.FromFilename("an2.mp4"));
                NSUserDefaults.StandardUserDefaults.SetBool(true, "SmallVidIntro");
            }

            avplayerItem        = new AVPlayerItem(avasset);
            avplayer            = new AVPlayer(avplayerItem);
            avplayerLayer       = AVPlayerLayer.FromPlayer(avplayer);
            avplayerLayer.Frame = View.Frame;
            View.Layer.AddSublayer(avplayerLayer);
            avplayer.Play();

            NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, MainScreenHandler);
        }
        private void LoadVideoDescView()
        {
            NSArray views = NSBundle.MainBundle.LoadNib("VoteVideoDescView", this, new NSDictionary());

            if (1 == views.Count)
            {
                UIView tempView = Runtime.GetNSObject(views.ValueAt(0)) as UIView;

                if (tempView is VoteImageDescView)
                {
                    var descView = tempView as VoteImageDescView;
                    descView.UpdateUIWith(SelectedVote);

                    descView.Frame = new System.Drawing.RectangleF(0, 0, (float)View.Bounds.Width, (float)View.Bounds.Height);
                    View.AddSubview(descView);

                    _asset      = AVAsset.FromUrl(NSUrl.FromString(SelectedVote.VideoUrl));
                    _playerItem = new AVPlayerItem(_asset);

                    _player            = new AVPlayer(_playerItem);
                    _playerLayer       = AVPlayerLayer.FromPlayer(_player);
                    _playerLayer.Frame = View.Frame;

                    descView.Layer.AddSublayer(_playerLayer);

                    _player.Play();
                }
            }
        }
예제 #10
0
        public MemoryStream GenerateThumbImage(string url, long usecond)
        {
            var asset          = AVAsset.FromUrl(NSUrl.FromFilename(url));
            var imageGenerator = AVAssetImageGenerator.FromAsset(asset);

            imageGenerator.AppliesPreferredTrackTransform = true;
            var actualTime = asset.Duration;

            CoreMedia.CMTime cmTime = new CoreMedia.CMTime(usecond, 2000000);
            NSError          error;
            var cgImage = imageGenerator.CopyCGImageAtTime(cmTime, out actualTime, out error);

            //AVAssetImageGenerator imageGenerator = new AVAssetImageGenerator(AVAsset.FromUrl((new Foundation.NSUrl(url))));
            //imageGenerator.AppliesPreferredTrackTransform = true;
            //var actualTime = asset.Duration;
            //CoreMedia.CMTime cmTime = new CoreMedia.CMTime(usecond, 1000000);
            //NSError error;
            //var cgImage = imageGenerator.CopyCGImageAtTime(cmTime, out actualTime, out error);
            //CMTime actualTime;
            //NSError error;
            //CGImage cgImage = imageGenerator.CopyCGImageAtTime(new CMTime(usecond, 1000000), out actualTime, out error);

            var zz = new UIImage(cgImage).AsJPEG().AsStream();
            var a  = new MemoryStream();

            zz.CopyTo(a);

            return(a);
            //return ImageSource.FromStream(() => new UIImage(cgImage).AsJPEG().AsStream()); //mageSource.FromStream(() => new UIImage(cgImage).AsPNG().AsStream());
        }
예제 #11
0
        private void SetSource()
        {
            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));
                }
            }

            if (asset != null)
            {
                _playerItem = new AVPlayerItem(asset);
            }
            else
            {
                _playerItem = null;
            }

            _player.ReplaceCurrentItemWithPlayerItem(_playerItem);

            if (_playerItem != null && Element.AutoPlay)
            {
                _player.Play();
            }
        }
예제 #12
0
        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);
        }
예제 #13
0
        private void Play(Uri uri)
        {
            var nsAsset       = AVAsset.FromUrl(DecodeUri(uri));
            var streamingItem = AVPlayerItem.FromAsset(nsAsset);

            _player.ReplaceCurrentItemWithPlayerItem(streamingItem);
        }
        public void queryiTunesLibraryForMediaItems(List <LibraryItem> libraryItems)
        {
#if ENABLE_ITUNES_ITEMS
            try
            {
                var mq        = new MPMediaQuery();
                var value     = NSNumber.FromInt32((int)MPMediaType.TypeAnyVideo);
                var predicate = MPMediaPropertyPredicate.PredicateWithValue(value, MPMediaItem.MediaTypeProperty);
                mq.AddFilterPredicate(predicate);

                List <MPMediaItem> mediaItems = new List <MPMediaItem>(mq.Items);
                foreach (MPMediaItem mediaItem in mediaItems)
                {
                    AVAsset asset = AVAsset.FromUrl(mediaItem.AssetURL);
                    if ((asset != null) && isRecording(asset))
                    {
                        LibraryItem libraryItem = new LibraryItem();
                        libraryItem.Storage       = LibraryItemStorage.iTunes;
                        libraryItem.ID            = mediaItem.PersistentID.ToString();
                        libraryItem.LocalFilePath = mediaItem.AssetURL.ToString();
                        fetchMetadata(asset, ref libraryItem);

                        libraryItems.Add(libraryItem);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log("ERROR: LocalLibrary.queryiTunesLibraryForMediaItems: " + ex);
            }
#endif
        }
예제 #15
0
        public void file(string Title, byte[] _byet)
        {
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string localFilename = "play.mov";  //same if I save the file as .mp4
            string localPath     = Path.Combine(documentsPath, localFilename);

            File.WriteAllBytes(localPath, _byet);



            _videobyte = _byet;

            this.Title = namefile = Title;

            local = localPath;

            avasset = AVAsset.FromUrl(NSUrl.FromFilename(localPath));
            var avplayerItem = new AVPlayerItem(avasset);
            var avplayer     = new AVPlayer(avplayerItem);

            avplayer.Play();
            this.Player = avplayer;
            // this.ShowsPlaybackControls = true;

            CoreMedia.CMTime m           = avplayer.CurrentTime;
            CMTime           duration    = avplayerItem.Duration;    //total time
            CMTime           currentTime = avplayerItem.CurrentTime; //playing time

            // this.Title =   avasset.Tracks..ToString();


            avplayer.Play();
        }
예제 #16
0
        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 LibraryItem libraryItemFromFile(string file)
        {
            using (AVAsset asset = AVAsset.FromUrl(NSUrl.FromFilename(file)))
            {
                if (isRecording(asset))
                {
                    LibraryItem libraryItem = new LibraryItem();
                    libraryItem.Storage       = LibraryItemStorage.AppLocal;
                    libraryItem.LocalFilePath = file;
                    fetchMetadata(asset, ref libraryItem);
                    return(libraryItem);
                }
                else
                {
                    Logger.Log($"WARNNING: {file} is not a MMT recording with valid PLVF flag. DELETING");
                    NSError error;
                    if (!NSFileManager.DefaultManager.Remove(NSUrl.FromFilename(file), out error))
                    {
                        Logger.Log($"WARNNING: Unable to delete {file}: " + error);
                    }
                }
            }

            return(null);
        }
        public void GenerateCGImagesAsynchronously()
        {
            // This test deadlocks on Mountain Lion (but works on Lion)
            // https://gist.github.com/rolfbjarne/1190d97af79e554c298f2c133dfd8e87
            TestRuntime.AssertSystemVersion(ApplePlatform.MacOSX, 10, 9, throwIfOtherPlatform: false);

            handled = false;
            mre     = new ManualResetEvent(false);
            ThreadStart main = () => {
                using (NSUrl video_url = NSUrl.FromFilename(video_asset_path))
                    using (AVAsset video_asset = AVAsset.FromUrl(video_url))
                        using (AVAssetImageGenerator aig = new AVAssetImageGenerator(video_asset)) {
                            NSValue[] values = new NSValue[] { NSValue.FromCMTime(CMTime.Zero) };
                            aig.GenerateCGImagesAsynchronously(values, handler);
                            mre.WaitOne();
                        }
            };
            var thread = new Thread(main)
            {
                IsBackground = true,
            };

            thread.Start();
            Assert.True(mre.WaitOne(2000), "wait");
            Assert.True(handled, "handled");
        }
        public static AVPlayerItem GetPlayerItem(this IMediaItem mediaItem)
        {
            AVAsset asset;

            if (mediaItem.MediaLocation == MediaLocation.Embedded)
            {
                string directory = Path.GetDirectoryName(mediaItem.MediaUri);
                string filename  = Path.GetFileNameWithoutExtension(mediaItem.MediaUri);
                string extension = Path.GetExtension(mediaItem.MediaUri).Substring(1);
                NSUrl  url       = NSBundle.MainBundle.GetUrlForResource(filename, extension, directory);
                asset = AVAsset.FromUrl(url);
            }
            else if (RequestHeaders != null && RequestHeaders.Any())
            {
                asset = AVUrlAsset.Create(NSUrl.FromString(mediaItem.MediaUri), GetOptionsWithHeaders(RequestHeaders));
            }
            else
            {
                asset = AVAsset.FromUrl(NSUrl.FromString(mediaItem.MediaUri));
            }

            var playerItem = AVPlayerItem.FromAsset(asset);

            return(playerItem);
        }
예제 #20
0
        partial void ChooseVideoTapped(UIBarButtonItem sender)
        {
            var videoPicker = new UIImagePickerController {
                ModalPresentationStyle = UIModalPresentationStyle.CurrentContext,
                SourceType             = UIImagePickerControllerSourceType.SavedPhotosAlbum,
                MediaTypes             = new string[] { UTType.Movie }
            };

            videoPicker.FinishedPickingMedia += (object s, UIImagePickerMediaPickedEventArgs e) => {
                displayLink.Paused = true;
                playButton.Title   = "Play";
                popover.Dismiss(true);

                outputFrames.Clear();
                presentationTimes.Clear();

                lastCallbackTime = 0.0;
                var asset = AVAsset.FromUrl(e.MediaUrl);

                if (assetReader != null && assetReader.Status == AVAssetReaderStatus.Reading)
                {
                    bufferSemaphore.Release();
                    assetReader.CancelReading();
                }

                backgroundQueue.DispatchAsync(() => ReadSampleBuffers(asset));
            };
            videoPicker.Canceled += (object s, EventArgs e) => DismissViewController(true, null);

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
            {
                popover = new UIPopoverController(videoPicker);
                popover.PresentFromBarButtonItem(sender, UIPopoverArrowDirection.Down, true);
            }
        }
예제 #21
0
 public static bool TryGenerateVideoThumbnail2(string localFile, CGSize size, out UIImage image, string extensionHint = ".mov")
 {
     image = null;
     try {
         const int secondToGet = 1;
         const int timeScale   = 60;
         var       asset       = AVAsset.FromUrl(NSUrl.FromFilename(localFile));
         var       generator   = new AVAssetImageGenerator(asset);
         var       time        = new CMTime(secondToGet, timeScale);
         CMTime    actualTime;
         NSError   error;
         var       cgImage = generator.CopyCGImageAtTime(time, out actualTime, out error);
         if (error == null)
         {
             image = new UIImage(cgImage);
             image = UIImageExtensions.ResizeAndDispose(image,
                                                        size,
                                                        ResizeMethod.AspectFill,
                                                        ResizeAlignment.CenterCenter
                                                        );
             return(true);
         }
     } catch {
     }
     return(false);
 }
        ///<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);
        }
        public Task <string> CreateThumbnailAsync(string videoPath)
        {
            return(Task.Run(() =>
            {
                var url = NSUrl.FromFilename(videoPath);
                var asset = AVAsset.FromUrl(url);
                var assetImageGenerator = AVAssetImageGenerator.FromAsset(asset);
                assetImageGenerator.AppliesPreferredTrackTransform = true;

                var time = CMTime.FromSeconds(1, 1);

                using (var img = assetImageGenerator.CopyCGImageAtTime(time, out CMTime _, out NSError __))
                {
                    if (img == null)
                    {
                        Debug.WriteLine($"Could not find file at url: {videoPath}");
                        return string.Empty;
                    }

                    var outputPath = Path.ChangeExtension(videoPath, ".png");
                    var fileUrl = NSUrl.FromFilename(outputPath);

                    using (var imageDestination = CGImageDestination.Create(fileUrl, UTType.PNG, 1))
                    {
                        imageDestination.AddImage(img);
                        imageDestination.Close();
                    }

                    return outputPath;
                }
            }));
        }
예제 #24
0
        /// <summary>
        /// Compress the video
        /// </summary>
        /// <param name="inputPath">Arquivo de Origem</param>
        /// <param name="outputPath">Arquivo de Destino</param>
        /// <returns></returns>
        public async Task CompressVideo(string inputPath, string outputPath, int bitrateMode = 10)
        {
            AVAssetExportSessionPreset quality = AVAssetExportSessionPreset.Preset1280x720;

            float bitrate = 0;

            //Delete compress video if exist
            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }

            //Buscar o bitrate do video
            try
            {
                NSUrl source     = NSUrl.FromFilename(inputPath);
                var   videoAsset = new AVUrlAsset(source);

                var videoTrack = videoAsset.Tracks.First(x => x.MediaType == AVMediaType.Video);
                bitrate = videoTrack.EstimatedDataRate;

                bitrate /= 1024;
            }
            catch { }

            //Define a qualidade
            bitrateMode = bitrateMode == 10 ? bitrateMode10 : bitrateMode2;

            if (bitrate > 0 && bitrate > bitrateMode)
            {
                float reduce = (float)bitrate / (float)bitrateMode;
                if (reduce > 6)
                {
                    quality = AVAssetExportSessionPreset.LowQuality;
                }
                else if (reduce > 1.1)
                {
                    quality = AVAssetExportSessionPreset.MediumQuality;
                }
            }

            //Comprime o vídeo
            try
            {
                var asset = AVAsset.FromUrl(NSUrl.FromFilename(inputPath));
                AVAssetExportSession export = new AVAssetExportSession(asset, quality);

                export.OutputUrl      = NSUrl.FromFilename(outputPath);
                export.OutputFileType = AVFileType.Mpeg4;
                export.ShouldOptimizeForNetworkUse = true;

                await RunExportAsync(export);
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine("Erro ao comprimir video");
            }

            return;
        }
예제 #25
0
파일: VideoUtils.cs 프로젝트: nour7/Ta7meel
        ImageSource IVideoUtils.GetVideoThumbnail(string url)
        {
            NSUrl videoUrl = NSUrl.CreateFileUrl(url, null);

            var asset          = AVAsset.FromUrl(videoUrl);
            var imageGenerator = AVAssetImageGenerator.FromAsset(asset);

            imageGenerator.AppliesPreferredTrackTransform = true;
            var seconds = asset.Duration.Seconds;

            CoreMedia.CMTime actualTime;
            CoreMedia.CMTime cmTime = asset.Duration;
            var timeScale           = asset.Duration.TimeScale;

            cmTime.Value = (seconds > 5) ? timeScale * 5 : timeScale * 1;
            NSError error;
            var     imageRef = imageGenerator.CopyCGImageAtTime(cmTime, out actualTime, out error);

            if (imageRef == null)
            {
                return(null);
            }

            var uiImage = UIImage.FromImage(imageRef);



            var img = Xamarin.Forms.ImageSource.FromStream(() => ((uiImage.AsPNG().AsStream())));


            return(img);
        }
예제 #26
0
        void UpdateUI()
        {
            var formsControl = Element as VideoImagePreview;

            if (formsControl == null)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(formsControl.VideoUrl))
            {
                var outputTime = new CMTime();
                var error      = new NSError();

                using (var asset = AVAsset.FromUrl(new NSUrl(formsControl.VideoUrl)))
                    using (var assetGenerator = AVAssetImageGenerator.FromAsset(asset))
                    {
                        var image = assetGenerator.CopyCGImageAtTime(new CMTime(0, 1), out outputTime, out error);

                        if (image != null)
                        {
                            Control?.InvokeOnMainThread(() => ((UIImageView)Control).Image = new UIImage(image));
                        }
                    }
            }
            else
            {
                formsControl.Source = "camera.png";
            }
        }
        //Simple Editor
        void setupEditingAndPlayback()
        {
            var path1  = NSBundle.MainBundle.PathForResource("sample_clip1", "m4v");
            var path2  = NSBundle.MainBundle.PathForResource("sample_clip2", "mov");
            var asset1 = AVAsset.FromUrl(new NSUrl(path1, false)) as AVUrlAsset;
            var asset2 = AVAsset.FromUrl(new NSUrl(path2, false)) as AVUrlAsset;

            DispatchGroup dispatchGroup = DispatchGroup.Create();

            string[] assetKeys =
            {
                "tracks",
                "duration",
                "composable"
            };

            loadAsset(asset1, assetKeys, dispatchGroup);
            loadAsset(asset2, assetKeys, dispatchGroup);

            // Wait until both assets are loaded
            dispatchGroup.Wait(DispatchTime.Forever);
            InvokeOnMainThread(delegate {
                synchronizeWithEditor();
            });
        }
예제 #28
0
        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;
        }
예제 #29
0
 public void LoadFromPath(string filePath)
 {
     if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
     {
         var url = NSUrl.CreateFileUrl(filePath, false, null);
         LoadFromAsset(AVAsset.FromUrl(url));
     }
 }
예제 #30
0
 private void Play(MediaPlaybackList playlist)
 {
     foreach (var item in playlist.Items)
     {
         var asset = AVAsset.FromUrl(DecodeUri(item.Source.Uri));
         _player.InsertItem(new AVPlayerItem(asset), null);
     }
 }