private void HandleAssetPersistenceManagerDidRestoreState(NSNotification obj)
        {
            foreach (var stream in StreamListManager.Current.Streams)
            {
                var asset = AssetPersistenceManager.Current.AssetForStream(stream.Name);

                if (asset != null)
                {
                    Assets.Add(asset);
                }
                else
                {
                    /*
                     * If an existing `AVURLAsset` is not available for an active
                     * download we then see if there is a file URL available to
                     * create an asset from.
                     */

                    asset = AssetPersistenceManager.Current.LocalAssetForStream(stream.Name);

                    if (asset != null)
                    {
                        Assets.Add(asset);
                    }
                    else
                    {
                        var urlAsset = new AVUrlAsset(new NSUrl(stream.PlaylistUrl));
                        asset = new Asset(stream, urlAsset);
                        Assets.Add(asset);
                    }
                }
            }

            NSNotificationCenter.DefaultCenter.PostNotificationName(AssetListManager.AssetListManagerDidLoad, this);
        }
        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);
        }
        private void LoadAsset(AVUrlAsset asset, string[] assetKeysToLoadandTest, DispatchGroup dispatchGroup)
        {
            dispatchGroup.Enter();
            asset.LoadValuesAsynchronously(assetKeysToLoadandTest, () => {
                foreach (string key in assetKeysToLoadandTest)
                {
                    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);
                CMTimeRange timeRange = new CMTimeRange()
                {
                    Start    = CMTime.FromSeconds(0, 1),
                    Duration = CMTime.FromSeconds(5, 1)
                };

                ClipTimeRanges.Add(NSValue.FromCMTimeRange(timeRange));
                dispatchGroup.Leave();
            });
        }
        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;
                }
            }
        }
        public OperationResult <Stream> GetFirstVideoFrame(string filePath)
        {
            var url            = NSUrl.CreateFileUrl(filePath, false, null);
            var asset          = new AVUrlAsset(url);
            var imageGenerator = new AVAssetImageGenerator(asset);

            imageGenerator.AppliesPreferredTrackTransform = true;

            CMTime  actualTime;
            NSError error;
            var     cgImage = imageGenerator.CopyCGImageAtTime(new CMTime(0, 1), out actualTime, out error);

            if (error != null)
            {
                return(OperationResult <Stream> .AsFailure(error.ToString()));
            }

            if (cgImage != null)
            {
                return(OperationResult <Stream> .AsSuccess(new UIImage(cgImage).AsJPEG().AsStream()));
            }
            else
            {
                return(OperationResult <Stream> .AsFailure("Image generation failed"));
            }
        }
Example #6
0
        internal static async Task <StorageItemThumbnail> CreateVideoThumbnailAsync(StorageFile file)
        {
            AVAsset asset = AVUrlAsset.FromUrl(NSUrl.FromFilename(file.Path));
            AVAssetImageGenerator generator = AVAssetImageGenerator.FromAsset(asset);

            generator.AppliesPreferredTrackTransform = true;
            NSError error;
            CMTime  actualTime;
            CMTime  time  = CMTime.FromSeconds(asset.Duration.Seconds / 2, asset.Duration.TimeScale);
            CGImage image = generator.CopyCGImageAtTime(time, out actualTime, out error);

#if __MAC__
            NSMutableData      buffer = new NSMutableData();
            CGImageDestination dest   = CGImageDestination.Create(buffer, UTType.JPEG, 1, null);
            dest.AddImage(image);
            return(new StorageItemThumbnail(buffer.AsStream()));
#else
            UIImage image2 = UIImage.FromImage(image);
            image.Dispose();

            UIImage image3 = image2.Scale(new CGSize(240, 240));
            image2.Dispose();

            return(new StorageItemThumbnail(image3.AsJPEG().AsStream()));
#endif
        }
Example #7
0
        private void AVAssetLoadComplete(string url, AVUrlAsset asset)
        {
            try
            {
                NSError err;
                var     value = asset.StatusOfValue(AVASSET_PLAYABLE_KEY, out err);
                switch (value)
                {
                case AVKeyValueStatus.Loaded:

                    DispatchQueue.MainQueue.DispatchSync(() =>
                    {
                        InitPlayerForeground(url, asset);
                    });
                    break;

                case AVKeyValueStatus.Failed:
                case AVKeyValueStatus.Cancelled:
                    Debug.WriteLine("FailPlaybackServiceInit");
                    break;

                default:
                    break;
                }
                Debug.WriteLine("Done AVAssetLoadComplete");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("FailAVAssetLoadComplete");
            }
        }
Example #8
0
        public async Task SetQueue(IList <Song> songs)
        {
            System.Diagnostics.Debug.WriteLine("SetQeueue()");
            await Task.Run(() =>
            {
                if (songs == null)
                {
                    songs = new ObservableCollection <Song>();
                }

                if (!Enumerable.SequenceEqual(_queue, songs, _comparer))
                {
                    _queue = songs;
                    _getQueue?.Invoke(_queue);
                }

                _pos = 0;
                _getQueuePos(_pos);
                try
                {
                    NSUrl url = new NSUrl(_queue[_pos].Uri);
                    NSMutableDictionary dict = new NSMutableDictionary();
                    dict.Add(new NSString("AVURLAssetPreferPreciseDurationAndTimingKey"), new NSNumber(true));
                    var playerItem = AVPlayerItem.FromAsset(AVUrlAsset.Create(url, new AVUrlAssetOptions(dict)));

                    _player.ReplaceCurrentItemWithPlayerItem(playerItem);
                    Pause();
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e);
                }
            });
        }
Example #9
0
        public void Start(int pos)
        {
            System.Diagnostics.Debug.WriteLine("Start()");

            // workaround to fix song auto-playing when app launches
            if (isFirst)
            {
                isFirst = false;
                return;
            }

            if (pos >= 0 && pos < _queue.Count)
            {
                _pos = pos;
                _getQueuePos(_pos);
                try
                {
                    NSUrl url = new NSUrl(_queue[_pos].Uri);
                    NSMutableDictionary dict = new NSMutableDictionary();
                    dict.Add(new NSString("AVURLAssetPreferPreciseDurationAndTimingKey"), new NSNumber(true));
                    var playerItem = AVPlayerItem.FromAsset(AVUrlAsset.Create(url, new AVUrlAssetOptions(dict)));
                    _player.ReplaceCurrentItemWithPlayerItem(playerItem);
                    NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, OnCompletion);
                    UpdateInfoCenter();
                    Play();
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e);
                }
            }
        }
Example #10
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;
        }
Example #11
0
        public Asset(Stream stream, AVUrlAsset urlAsset)
        {
            this.Stream   = stream;
            this.UrlAsset = urlAsset;

            if (Stream.IsProtected)
            {
                ContentKeyManager.Current.ContentKeySession?.Add(UrlAsset);
            }
        }
Example #12
0
        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;
                }
            }
        }
        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 options = MediaFileUrlHelper.GetOptionsWithHeaders(RequestHeaders);

                var nsAsset       = AVUrlAsset.Create(nsUrl, options);
                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;
        }
Example #14
0
        public override async Task <bool> PrepareData(PlaybackData data, bool isPlaying)
        {
            playbackData = data;
            stateObserver?.Dispose();
            stateObserver = null;
            CurrentSongId = data.SongId;
            AVPlayerItem playerItem       = null;
            var          songPlaybackData = data.SongPlaybackData;

            if (songPlaybackData.IsLocal || songPlaybackData.CurrentTrack.ServiceType == MusicPlayer.Api.ServiceType.iPod)
            {
                if (songPlaybackData.Uri == null)
                {
                    return(false);
                }
                var url = string.IsNullOrWhiteSpace(songPlaybackData?.CurrentTrack?.FileLocation) ? new NSUrl(songPlaybackData.Uri.AbsoluteUri) : NSUrl.FromFilename(songPlaybackData.CurrentTrack.FileLocation);
                playerItem = AVPlayerItem.FromUrl(url);
                await playerItem.WaitStatus();
            }
            else
            {
#if HttpPlayback
                var urlEndodedSongId = HttpUtility.UrlEncode(data.SongId);
                var url = $"http://localhost:{LocalWebServer.Shared.Port}/api/GetMediaStream/Playback?SongId={urlEndodedSongId}";
                playerItem = AVPlayerItem.FromUrl(new NSUrl(url));
#else
                NSUrlComponents comp =
                    new NSUrlComponents(
                        NSUrl.FromString(
                            $"http://localhost/{songPlaybackData.CurrentTrack.Id}.{data.SongPlaybackData.CurrentTrack.FileExtension}"), false);
                comp.Scheme = "streaming";
                if (comp.Url != null)
                {
                    var asset = new AVUrlAsset(comp.Url, new NSDictionary());
                    asset.ResourceLoader.SetDelegate(resourceDelegate, DispatchQueue.MainQueue);
                    playerItem    = new AVPlayerItem(asset, (NSString)"duration");
                    stateObserver = playerItem.AddObserver("status", NSKeyValueObservingOptions.New, (obj) =>
                    {
                        if (shouldBePlaying)
                        {
                            player.Play();
                        }
                        Console.WriteLine($"Player Status {playerItem.Status}");
                    });
                }
#endif
            }
            player.ReplaceCurrentItemWithPlayerItem(playerItem);
            IsPrepared = true;

            return(true);
        }
        void HandleVideo(MediaFile file)
        {
            if (file == null)
            {
                return;
            }
            var mediaUrl           = file.Path;
            var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var outputFile         = Path.Combine(documentsDirectory, Guid.NewGuid().ToString() + ".mp4");

            AVUrlAsset           asset         = new AVUrlAsset(NSUrl.CreateFileUrl(new string[] { mediaUrl }));
            AVAssetExportSession exportSession = new AVAssetExportSession(asset, AVAssetExportSession.Preset1280x720);
            var fileUrl = NSUrl.CreateFileUrl(new string[] { outputFile });

            exportSession.OutputUrl      = NSUrl.CreateFileUrl(new string[] { outputFile });
            exportSession.OutputFileType = AVFileType.Mpeg4;
            LoadingScreen.Show();
            LoadingScreen.SetText("Converting");
            exportSession.ExportAsynchronously(() =>
            {
                InvokeOnMainThread(() =>
                {
                    if (exportSession.Error != null)
                    {
                        int i = 3;
                    }

                    AVUrlAsset asset2 = new AVUrlAsset(NSUrl.CreateFileUrl(new string[] { mediaUrl }));
                    AVAssetImageGenerator generator = new AVAssetImageGenerator(asset2);

                    generator.AppliesPreferredTrackTransform = true;
                    var thumbTime  = new CMTime(0, 30);
                    NSValue[] vals = new NSValue[] { NSValue.FromCMTime(thumbTime) };
                    CGSize maxSize = new CGSize(800, 600);
                    //generator.MaximumSize = maxSize;
                    generator.GenerateCGImagesAsynchronously(vals, (requestedTime, imageRef, actualTime, result, error) =>
                    {
                        var previewImage = System.IO.Path.Combine(documentsDirectory, Guid.NewGuid() + ".jpg");
                        NSError err;

                        UIImage.FromImage(new CGImage(imageRef)).AsJPEG(.75f).Save(previewImage, false, out err);

                        InvokeOnMainThread(() =>
                        {
                            LoadingScreen.Hide();

                            VideoPicked?.Invoke(outputFile, previewImage);
                        });
                    });
                });
            });
        }
Example #16
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            string url = "https://aod-rfi.akamaized.net/savoirs/apprendre/actu/jff/jff-28102020.mp3";
            // Perform any additional setup after loading the view, typically from a nib.
            var asset = new AVUrlAsset(
                NSUrl.FromString(url),
                new AVUrlAssetOptions(NSDictionary.FromObjectAndKey(
                                          NSNumber.FromBoolean(true),
                                          AVUrlAsset.PreferPreciseDurationAndTimingKey)));

            asset.LoadValuesAsynchronously(new string[] { AVASSET_PLAYABLE_KEY }, () => AVAssetLoadComplete(url, asset));
        }
Example #17
0
        public void Init(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return;
            }

            var asset = new AVUrlAsset(
                NSUrl.FromString(url),
                new AVUrlAssetOptions(NSDictionary.FromObjectAndKey(
                                          NSNumber.FromBoolean(true),
                                          AVUrlAsset.PreferPreciseDurationAndTimingKey)));

            asset.LoadValuesAsynchronously(new string[] { AVASSET_PLAYABLE_KEY }, () => AVAssetLoadComplete(url, asset));
        }
Example #18
0
        void SetupPlayback()
        {
            var movieURL = NSBundle.MainBundle.GetUrlForResource("samplemovie", "mov");
            var asset    = new AVUrlAsset(movieURL, (AVUrlAssetOptions)null);

            // Create a new `AVPlayerItem` and make it our player's current item.
            //
            // Using `AVAsset` now runs the risk of blocking the current thread (the
            // main UI thread) whilst I/O happens to populate the properties. It's prudent
            // to defer our work until the properties we need have been loaded.
            //
            // These properties can be passed in at initialization to `AVPlayerItem`,
            // which are then loaded automatically by `AVPlayer`.
            PlayerItem = new AVPlayerItem(asset, assetKeysRequiredToPlay);
        }
Example #19
0
        static AVPlayerItem CreateOnboardingChartItem()
        {
            var mediaElementService = ContainerService.Container.Resolve <MediaElementService>();

            if (mediaElementService.OnboardingChart?.HlsUrl is null)
            {
                throw new NullReferenceException();
            }

            var asset = AVUrlAsset.Create(NSUrl.FromString(mediaElementService.OnboardingChart.HlsUrl));

            return(new AVPlayerItem(asset)
            {
                PreferredForwardBufferDuration = 1,
            });
        }
        /// <summary>
        /// Init player to url with token
        /// </summary>
        /// <param name="url"></param>
        private async void InitPlayer(string url)
        {
            // Get Token
            var handler = new CustomDelegatingHandler();
            var header  = await handler.GetToken(url);

            _soundUrl = NSUrl.FromString(url);

            NSMutableDictionary headers = new NSMutableDictionary();

            headers.SetValueForKey(NSObject.FromObject(header), new NSString("Authorization"));
            var dict  = new NSDictionary(@"AVURLAssetHTTPHeaderFieldsKey", headers);
            var asset = new AVUrlAsset(_soundUrl, dict);

            AVPlayerItem item = new AVPlayerItem(asset);

            _player = AVPlayer.FromPlayerItem(item);
        }
Example #21
0
        public static async Task <NSUrl> CropVideoAsync(NSUrl url, nfloat startTime, nfloat durationTime)
        {
            // get output url
            var outputURL = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            if (!Directory.Exists(outputURL))
            {
                Directory.CreateDirectory(outputURL);
            }
            outputURL = Path.Combine(outputURL, "output.mp4");
            try
            {
                File.Delete(outputURL);
            }
            catch
            {
                Debug.WriteLine("Export failed to remove destination file");
                return(null);
            }

            // set up for export
            var asset         = new AVUrlAsset(url, (AVUrlAssetOptions)null);
            var exportSession = new AVAssetExportSession(asset, AVAssetExportSession.PresetHighestQuality);

            exportSession.OutputUrl = new NSUrl(outputURL, false);
            exportSession.ShouldOptimizeForNetworkUse = true;
            exportSession.OutputFileType = AVFileType.Mpeg4;
            exportSession.TimeRange      = new CMTimeRange
            {
                Start    = CMTime.FromSeconds(startTime, 600),
                Duration = CMTime.FromSeconds(durationTime, 600)
            };

            // export
            await exportSession.ExportTaskAsync();

            if (exportSession.Status != AVAssetExportSessionStatus.Completed)
            {
                Debug.WriteLine("Export failed: " + exportSession.Status);
                return(null);
            }

            return(exportSession.OutputUrl);
        }
Example #22
0
            void GetAssetFromUrl(Foundation.NSUrl url)
            {
                try
                {
                    var    inputPath  = url;
                    var    outputPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/output.mp3";
                    var    outputURL  = new NSUrl(outputPath);
                    NSData data       = NSData.FromUrl(outputURL);

                    //compress the video file
                    var asset         = new AVUrlAsset(inputPath, (AVUrlAssetOptions)null);
                    var exportSession = AVAssetExportSession.FromAsset(asset, "AVAssetExportPresetLowQuality");

                    exportSession.OutputUrl      = outputURL;
                    exportSession.OutputFileType = AVFileType.CoreAudioFormat;

                    exportSession.ExportAsynchronously(() =>
                    {
                        Console.WriteLine(exportSession.Status);                        //prints status "Failed"....

                        exportSession.Dispose();
                    });
                    //var asset = new ALAssetsLibrary();
                    //UIImage image;
                    //asset.AssetForUrl(
                    //   url,
                    //   (ALAsset obj) =>
                    //   {
                    //   var assetRep = obj.DefaultRepresentation;
                    //   var filename = assetRep.Filename;


                    //   },
                    //   (NSError err) =>
                    //   {
                    //   Console.WriteLine(err);
                    //   }
                    //   );
                }
                catch (Exception ex)
                {
                }
            }
        private AVPlayerItem GetPlayerItem(NSUrl url)
        {
            AVAsset asset;

            if (RequestHeaders != null && RequestHeaders.Any())
            {
                var options = GetOptionsWithHeaders(RequestHeaders);

                asset = AVUrlAsset.Create(url, options);
            }
            else
            {
                asset = AVAsset.FromUrl(url);
            }

            var playerItem = AVPlayerItem.FromAsset(asset);

            return(playerItem);
        }
        public UIImage Generate(CGSize size)
        {
            var asset     = new AVUrlAsset(Url);
            var generator = new AVAssetImageGenerator(asset)
            {
                AppliesPreferredTrackTransform = true,
                MaximumSize = new CGSize(size.Width * UIScreen.MainScreen.Scale, size.Height * UIScreen.MainScreen.Scale)
            };

            var     actualTime = new CMTime(0, 1000);
            NSError error      = null;
            var     cgImage    = generator.CopyCGImageAtTime(new CMTime(1, 1000), out actualTime, out error);

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

            return(new UIImage(cgImage));
        }
Example #25
0
 private void InitPlayerForeground(string url, AVUrlAsset asset)
 {
     playEndHandle = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, HandlePlayEnd);
     if (Player == null)
     {
         currentItem = new AVPlayerItem(asset);
         Player      = new AVPlayer(currentItem);
         Player.AddPeriodicTimeObserver(new CMTime(1, 1), DispatchQueue.MainQueue, TimeUpdate);
     }
     else
     {
         currentItem.Dispose();
         currentItem = new AVPlayerItem(
             new AVUrlAsset(NSUrl.FromString(url),
                            new AVUrlAssetOptions(NSDictionary.FromObjectAndKey(
                                                      NSNumber.FromBoolean(true),
                                                      AVUrlAsset.PreferPreciseDurationAndTimingKey))));
         Player.ReplaceCurrentItemWithPlayerItem(currentItem);
     }
 }
        private void SetupEditingAndPlayback()
        {
            string path1 = NSBundle.MainBundle.PathForResource("sample_clip1", "m4v");
            string path2 = NSBundle.MainBundle.PathForResource("sample_clip2", "mov");

            var asset1 = AVUrlAsset.FromUrl(new NSUrl(path1, false)) as AVUrlAsset;
            var asset2 = AVUrlAsset.FromUrl(new NSUrl(path2, false)) as AVUrlAsset;

            var dispatchGroup = DispatchGroup.Create();

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

            LoadAsset(asset1, assetKeysToLoadandTest, dispatchGroup);
            LoadAsset(asset2, assetKeysToLoadandTest, dispatchGroup);

            dispatchGroup.DispatchAsync(DispatchQueue.MainQueue, SynchronizeWithEditor);
        }
Example #27
0
        /// <summary>
        /// Check bitrate video is bigger than 2 or 10
        /// </summary>
        /// <param name="srcPath">Video file path</param>
        /// <param name="bitrateMode">Max bitrate allowed</param>
        /// <returns></returns>
        public bool NeedCompress(string srcPath, int bitrateMode = 10)
        {
            //Define a compressão padrão para alta
            bitrateMode = bitrateMode == 10 ? bitrateMode10 : bitrateMode2;

            NSUrl source = NSUrl.FromFilename(srcPath);

            var videoAsset = new AVUrlAsset(source);

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

                bitrate /= 1024;
                return(bitrate > bitrateMode);
            }
            catch { }

            return(false);
        }
Example #28
0
        public override async Task <bool> PrepareData(PlaybackData data, bool isPlaying)
        {
            CurrentSongId = data.SongId;
            AVPlayerItem playerItem   = null;
            var          playbackData = data.SongPlaybackData;

            if (playbackData.IsLocal || playbackData.CurrentTrack.ServiceType == MusicPlayer.Api.ServiceType.iPod)
            {
                if (playbackData.Uri == null)
                {
                    return(false);
                }
                var url = string.IsNullOrWhiteSpace(playbackData?.CurrentTrack?.FileLocation) ? new NSUrl(playbackData.Uri.AbsoluteUri) : NSUrl.FromFilename(playbackData.CurrentTrack.FileLocation);
                playerItem = AVPlayerItem.FromUrl(url);
                await playerItem.WaitStatus();
            }
            else
            {
#if HttpPlayback
                var urlEndodedSongId = HttpUtility.UrlEncode(data.SongId);
                var url = $"http://localhost:{LocalWebServer.Shared.Port}/api/GetMediaStream/Playback?SongId={urlEndodedSongId}";
                playerItem = AVPlayerItem.FromUrl(new NSUrl(url));
#else
                NSUrlComponents comp =
                    new NSUrlComponents(
                        NSUrl.FromString(
                            $"http://localhost/{playbackData.CurrentTrack.Id}.{data.SongPlaybackData.CurrentTrack.FileExtension}"), false);
                comp.Scheme = "streaming";
                if (comp.Url != null)
                {
                    var asset = new AVUrlAsset(comp.Url, new NSDictionary());
                    asset.ResourceLoader.SetDelegate(NativeAudioPlayer.LoaderDelegate, DispatchQueue.MainQueue);
                    playerItem = new AVPlayerItem(asset);
                }
#endif
            }
            player.ReplaceCurrentItemWithPlayerItem(playerItem);
            IsPrepared = true;
            return(true);
        }
        private void compressVideo(NSUrl inputURL, NSUrl outputURL)
        {
            NSUrl url      = inputURL;
            var   urlAsset = new AVUrlAsset(inputURL);
            AVAssetExportSession exportSession = new AVAssetExportSession(urlAsset, AVAssetExportSessionPreset.MediumQuality);

            exportSession.OutputUrl      = outputURL;
            exportSession.OutputFileType = AVFileType.QuickTimeMovie;
            exportSession.ShouldOptimizeForNetworkUse = true;

            exportSession.ExportAsynchronously(() =>
            {
                NSData data      = NSData.FromUrl(outputURL);
                byte[] dataBytes = new byte[data.Length];
                System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));
                UIApplication.SharedApplication.InvokeOnMainThread(delegate
                {
                    (Element as CustomVideoCamera).SetPhotoResult(outputURL.ToString(), dataBytes, 0, 0);
                    activityIndicator.StopAnimating();
                });
            });
        }
        /// <summary>
        /// This function demonstrates returns the next <c>AVMediaSelectionGroup</c> and
        /// <c>AVMediaSelectionOption</c> that should be downloaded if needed. This is done
        /// by querying an <c>AVURLAsset</c>'s <c>AVAssetCache</c> for its available <c>AVMediaSelection</c>
        /// and comparing it to the remote versions.
        /// </summary>
        /// <returns>The media selection.</returns>
        /// <param name="asset">Asset.</param>
        Tuple <AVMediaSelectionGroup, AVMediaSelectionOption> nextMediaSelection(AVUrlAsset asset)
        {
            //guard let assetCache = asset.assetCache else { return (nil, nil) }
            var assetCache = asset.Cache;

            if (assetCache == null)
            {
                return(new Tuple <AVMediaSelectionGroup, AVMediaSelectionOption> (null, null));
            }

            var mediaCharacteristics = new [] { AVMediaCharacteristic.Audible, AVMediaCharacteristic.Legible };

            foreach (var mediaCharacteristic in mediaCharacteristics)
            {
                var mediaSelectionGroup = asset.MediaSelectionGroupForMediaCharacteristic(mediaCharacteristic);

                if (mediaSelectionGroup != null)
                {
                    var savedOptions = assetCache.GetMediaSelectionOptions(mediaSelectionGroup);

                    if (savedOptions.Length < mediaSelectionGroup.Options.Length)
                    {
                        // There are still media options left to download.
                        foreach (var option in mediaSelectionGroup.Options)
                        {
                            if (!savedOptions.Contains(option))
                            {
                                // This option has not been download.
                                return(new Tuple <AVMediaSelectionGroup, AVMediaSelectionOption> (mediaSelectionGroup, option));
                            }
                        }
                    }
                }
            }

            // At this point all media options have been downloaded.
            return(new Tuple <AVMediaSelectionGroup, AVMediaSelectionOption> (null, null));
        }
		void SetupPlayback()
		{
			var movieURL = NSBundle.MainBundle.GetUrlForResource ("samplemovie", "mov");
			var asset = new AVUrlAsset (movieURL, (AVUrlAssetOptions)null);

			// Create a new `AVPlayerItem` and make it our player's current item.
			//
			// Using `AVAsset` now runs the risk of blocking the current thread (the
			// main UI thread) whilst I/O happens to populate the properties. It's prudent
			// to defer our work until the properties we need have been loaded.
			//
			// These properties can be passed in at initialization to `AVPlayerItem`,
			// which are then loaded automatically by `AVPlayer`.
			PlayerItem = new AVPlayerItem (asset, assetKeysRequiredToPlay);
		}
		private void LoadAsset (AVUrlAsset asset, string[] assetKeysToLoadandTest, DispatchGroup dispatchGroup)
		{
			dispatchGroup.Enter ();
			asset.LoadValuesAsynchronously (assetKeysToLoadandTest, () => {
				foreach (string key in assetKeysToLoadandTest) {
					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);
				CMTimeRange timeRange = new CMTimeRange () {
					Start = CMTime.FromSeconds (0, 1),
					Duration = CMTime.FromSeconds (5, 1)
				};

				ClipTimeRanges.Add (NSValue.FromCMTimeRange (timeRange));
				dispatchGroup.Leave ();
			});
		}