Exemplo n.º 1
0
        FileData GetMovieMediaFile(NSDictionary info)
        {
            var url = info[UIImagePickerController.MediaURL] as NSUrl;

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

            AVUrlAsset asset = new AVUrlAsset(url);

            // 文件描述
            var      track = asset.GetTracks(AVMediaTypes.Video)[0];
            TimeSpan ts    = TimeSpan.FromSeconds(track.TimeRange.Duration.Seconds);
            string   desc  = $"{ts.Minutes.ToString("D2")}:{ts.Seconds.ToString("D2")}";

            // 生成缩略图
            string thumbPath = null;
            var    segs      = track.Segments;

            if (segs != null && segs.Length > 0)
            {
                CMTime startTime = CMTime.Invalid;
                for (int i = 0; i < segs.Length; i++)
                {
                    if (!segs[i].Empty)
                    {
                        startTime = segs[i].TimeMapping.Target.Start;
                        break;
                    }
                }

                if (!startTime.IsInvalid)
                {
                    var assetGen = new AVAssetImageGenerator(asset);
                    assetGen.AppliesPreferredTrackTransform = true;
                    using (var firstImg = assetGen.CopyCGImageAtTime(startTime, out var r, out var error))
                    {
                        if (error == null)
                        {
                            UIImage img = new UIImage(firstImg);
                            desc     += $" ({img.CGImage.Width} x {img.CGImage.Height})";
                            thumbPath = CreateThumbnail(img, true);
                        }
                    }
                }
            }

            var path = System.IO.Path.Combine(Kit.CachePath, Kit.NewGuid + ".mp4");

            try
            {
                File.Move(url.Path, path);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Unable to move file, trying to copy. {ex.Message}");
                try
                {
                    File.Copy(url.Path, path);
                    File.Delete(url.Path);
                }
                catch (Exception)
                {
                    Debug.WriteLine($"Unable to copy/delete file, will be left around :( {ex.Message}");
                }
            }

            var fd = new FileData(path, System.IO.Path.GetFileName(path), (ulong)new FileInfo(path).Length);

            fd.Desc      = desc;
            fd.ThumbPath = thumbPath;
            return(fd);
        }