Пример #1
0
        private async void Select_OnClick(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker {
                SuggestedStartLocation = PickerLocationId.Desktop
            };

            picker.FileTypeFilter.Add(".mp4");

            var pickedFiles = await picker.PickMultipleFilesAsync();

            if (pickedFiles == null)
            {
                return;
            }

            TextBlock.Text = $"Importing {pickedFiles.Count} files";

            composition = new MediaComposition();
            var files = pickedFiles.OrderBy(x => x.Name).ToArray();

            foreach (var file in files)
            {
                var clip = await MediaClip.CreateFromFileAsync(file);

                composition.Clips.Add(clip);
                TextBlock.Text = $"Importing {Path.GetFileName(file.Path)}";
            }

            TextBlock.Text = $"All files are imported";
        }
Пример #2
0
        public async void CaptureVideo()
        {
            //<SnippetCaptureVideo>
            CameraCaptureUI captureUI = new CameraCaptureUI();

            captureUI.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;

            StorageFile videoFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Video);

            if (videoFile == null)
            {
                // User cancelled photo capture
                return;
            }
            //</SnippetCaptureVideo>

            //<SnippetAddToComposition>
            MediaClip mediaClip = await MediaClip.CreateFromFileAsync(videoFile);

            mediaComposition.Clips.Add(mediaClip);
            mediaStreamSource = mediaComposition.GeneratePreviewMediaStreamSource(
                (int)mediaElement.ActualWidth,
                (int)mediaElement.ActualHeight);
            //</SnippetAddToComposition>

            //<SnippetSetMediaElementSource>
            mediaElement.SetMediaStreamSource(mediaStreamSource);
            //</SnippetSetMediaElementSource>
        }
Пример #3
0
        private async void addVideoButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file;
            IReadOnlyList <StorageFile> files;

            files = await LoadFile("single", ".mp4");

            if (files.Count != 0)
            {
                file = files[0];
                if (file.ContentType == "video/mp4")
                {
                    _videoFile = file;
                    selectedVideoFileTextBlock.Text = _videoFile.DisplayName;
                    _video = await MediaClip.CreateFromFileAsync(_videoFile);

                    SetTimeSliders(_video.OriginalDuration);
                    GenerateButtonEnable();
                    var enc = _video.GetVideoEncodingProperties();
                    Resolutions = new SavingResolutionsCollection(enc);
                    saveResolutionSelector.ItemsSource   = Resolutions;
                    saveResolutionSelector.SelectedIndex = 0;

                    AllowToWatchVideoBeforeGenerating(true);
                }
            }
        }
Пример #4
0
        private async void SelectedVideo_Drop(object sender, DragEventArgs e)
        {
            if (e.DataView.Contains(StandardDataFormats.StorageItems))
            {
                var items = await e.DataView.GetStorageItemsAsync();

                if (items.Count > 0)
                {
                    var file = items[0] as StorageFile;
                    if (file.ContentType == "video/mp4" || file.ContentType == "video/x-matroska")
                    {
                        _videoFile = file;
                        selectedVideoFileTextBlock.Text = _videoFile.DisplayName;
                        _video = await MediaClip.CreateFromFileAsync(_videoFile);

                        SetTimeSliders(_video.OriginalDuration);
                        GenerateButtonEnable();
                        var enc = _video.GetVideoEncodingProperties();
                        Resolutions = new SavingResolutionsCollection(enc);
                        saveResolutionSelector.ItemsSource   = Resolutions;
                        saveResolutionSelector.SelectedIndex = 0;

                        AllowToWatchVideoBeforeGenerating(true);
                    }
                }
            }
            GenerateButtonEnable();
        }
Пример #5
0
        private async void VideoEditDialog_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Composition = new MediaComposition();
                VideoClip   = await MediaClip.CreateFromFileAsync(VideoFile);

                Composition.Clips.Add(VideoClip);

                PreviewSource    = MediaSource.CreateFromMediaStreamSource(Composition.GeneratePreviewMediaStreamSource(640, 360));
                MediaPlay.Source = PreviewSource;

                CutRange.Maximum  = VideoClip.OriginalDuration.TotalMilliseconds;
                CutRange.RangeMax = CutRange.Maximum;
            }
            catch
            {
                Hide();

                QueueContentDialog dialog = new QueueContentDialog
                {
                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                    Content         = Globalization.GetString("QueueDialog_EditErrorWhenOpen_Content"),
                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                };

                _ = await dialog.ShowAsync().ConfigureAwait(false);
            }
        }
Пример #6
0
        private async void AddAudio_Click(object sender, RoutedEventArgs e)
        {
            // Create the original MediaComposition
            var clip = await MediaClip.CreateFromFileAsync(pickedFile);

            composition = new MediaComposition();
            composition.Clips.Add(clip);

            // Add background audio
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
            picker.FileTypeFilter.Add(".mp3");
            picker.FileTypeFilter.Add(".wav");
            picker.FileTypeFilter.Add(".flac");
            var audioFile = await picker.PickSingleFileAsync();

            if (audioFile == null)
            {
                rootPage.NotifyUser("File picking cancelled", NotifyType.ErrorMessage);
                return;
            }

            var backgroundTrack = await BackgroundAudioTrack.CreateFromFileAsync(audioFile);

            composition.BackgroundAudioTracks.Add(backgroundTrack);

            // Render to MediaElement
            mediaElement.Position = TimeSpan.Zero;
            mediaStreamSource     = composition.GeneratePreviewMediaStreamSource((int)mediaElement.ActualWidth, (int)mediaElement.ActualHeight);
            mediaElement.SetMediaStreamSource(mediaStreamSource);

            rootPage.NotifyUser("Background audio added", NotifyType.StatusMessage);
        }
Пример #7
0
        public static async Task <ImageSource> GetPreviewBitmapAsync(StorageFile sourceFile, int requestedMinSide = 1280)
        {
            try
            {
                if (sourceFile.ContentType.Equals("video/mp4"))
                {
                    var props = await sourceFile.Properties.GetVideoPropertiesAsync();

                    var composition = new MediaComposition();
                    var clip        = await MediaClip.CreateFromFileAsync(sourceFile);

                    composition.Clips.Add(clip);

                    using (var imageStream = await composition.GetThumbnailAsync(TimeSpan.Zero, (int)props.GetWidth(), (int)props.GetHeight(), VideoFramePrecision.NearestKeyFrame))
                    {
                        return(await GetPreviewBitmapAsync(imageStream, requestedMinSide));
                    }
                }

                using (var imageStream = await sourceFile.OpenReadAsync())
                {
                    return(await GetPreviewBitmapAsync(imageStream, requestedMinSide));
                }
            }
            catch
            {
                return(null);
            }
        }
Пример #8
0
        private async void specialVideo_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
            picker.FileTypeFilter.Add(".mov");
            picker.FileTypeFilter.Add(".mp4");
            StorageFile pickedFilespecial = await picker.PickSingleFileAsync();

            if (pickedFilespecial == null)
            {
                return;
            }
            var clip = await MediaClip.CreateFromFileAsync(pickedFilespecial);

            composition = new MediaComposition();
            composition.Clips.Add(clip);
            var videoEffectDefinition = new VideoEffectDefinition("VideoEffectComponent.ExampleVideoEffect", new PropertySet()
            {
                { "FadeValue", .9 }
            });

            clip.VideoEffectDefinitions.Add(videoEffectDefinition);
            MediaStreamSource mediaStreamSource = composition.GenerateMediaStreamSource();

            mediaElement.SetMediaStreamSource(mediaStreamSource);
        }
Пример #9
0
        private async void CreateOverlays()
        {
            var baseVideoClip = await MediaClip.CreateFromFileAsync(baseVideoFile);

            composition = new MediaComposition();
            composition.Clips.Add(baseVideoClip);

            var overlayVideoClip = await MediaClip.CreateFromFileAsync(overlayVideoFile);

            // Overlay video in upper left corner, retain its native aspect ratio
            Rect videoOverlayPosition;
            var  encodingProperties = overlayVideoClip.GetVideoEncodingProperties();

            videoOverlayPosition.Height = mediaElement.ActualHeight / 3;
            videoOverlayPosition.Width  = (double)encodingProperties.Width / (double)encodingProperties.Height * videoOverlayPosition.Height;
            videoOverlayPosition.X      = 0;
            videoOverlayPosition.Y      = 0;

            var videoOverlay = new MediaOverlay(overlayVideoClip);

            videoOverlay.Position = videoOverlayPosition;
            videoOverlay.Opacity  = 0.75;

            var overlayLayer = new MediaOverlayLayer();

            overlayLayer.Overlays.Add(videoOverlay);
            composition.OverlayLayers.Add(overlayLayer);

            // Render to MediaElement
            mediaElement.Position = TimeSpan.Zero;
            mediaStreamSource     = composition.GeneratePreviewMediaStreamSource((int)mediaElement.ActualWidth, (int)mediaElement.ActualHeight);
            mediaElement.SetMediaStreamSource(mediaStreamSource);
        }
Пример #10
0
        /**
         * ターゲットの動画ファイルをセットする
         */
        public async void SetSource(StorageFile source)
        {
            Reset();

            if (null == source)
            {
                return;
            }
            mPlayer.SetSource(source);


            try
            {
                mClip = await MediaClip.CreateFromFileAsync(source);

                mTrimmingSlider.TotalRange = mClip.OriginalDuration.TotalMilliseconds;
                await mExtractor.ExtractAsync(mClip, (s, i, img) =>
                {
                    mFrameListView.Frames[i] = img;
                },
                                              (s, img) =>
                {
                    mFrameListView.FrameListHeight = mExtractor.ThumbnailHeight;
                    for (int i = 0; i < mExtractor.FrameCount; i++)
                    {
                        mFrameListView.Frames.Add(img);
                    }
                });
            }
            catch (Exception e)
            {
                CmLog.error("WvvFrameSelectorView.SetSource", e);
                Error.SetError(e);
            }
        }
Пример #11
0
        private static async Task <MediaClip> AddClipAsync(StorageFile pickedFile, PanelElement element)
        {
            MediaClip clip;

            if (element.FileType == FileType.Picture)
            {
                using (StorageItemThumbnail thumbnail = await pickedFile.GetThumbnailAsync(ThumbnailMode.PicturesView))
                {
                    if (thumbnail != null)
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(thumbnail);

                        element.Thumbnail = bitmapImage;
                    }
                }
                clip = await MediaClip.CreateFromImageFileAsync(pickedFile, TimeSpan.FromSeconds(5));
            }
            else
            {
                using (StorageItemThumbnail thumbnail = await pickedFile.GetThumbnailAsync(ThumbnailMode.VideosView))
                {
                    if (thumbnail != null)
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(thumbnail);

                        element.Thumbnail = bitmapImage;
                    }
                }
                clip = await MediaClip.CreateFromFileAsync(pickedFile);
            }

            return(clip);
        }
Пример #12
0
        async Task <MediaStreamSource> OpenVideo()
        {
            this.progressText.Text = "Downloading video...";

            var thumbnailFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Logo.scale-100.png"));

            var thumbnail = RandomAccessStreamReference.CreateFromFile(thumbnailFile);

            var url = "http://video.ch9.ms/ch9/4597/8db5a656-b173-4897-b2aa-e2075fb24597/windows10recap.mp4";

            var file = await StorageFile.CreateStreamedFileFromUriAsync(
                "windows10recap.mp4",
                new Uri(url),
                thumbnail);

            this.progressText.Text = "Creating clip...";
            var clip = await MediaClip.CreateFromFileAsync(file);

            clip.VideoEffectDefinitions.Add(new VideoEffectDefinition(typeof(ExampleVideoEffect).FullName));

            var composition = new MediaComposition();

            composition.Clips.Add(clip);

            if (ThumbnailGenerator.IsDrawingThumbnail)
            {
                customThumbnail = await composition.GetThumbnailAsync(TimeSpan.FromSeconds(10), 1280, 720, VideoFramePrecision.NearestFrame);
            }

            return(composition.GenerateMediaStreamSource());
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var videoFile = e.Parameter as StorageFile;

            if (videoFile != null)
            {
                StatusTextBlock.Text = videoFile.DisplayName;

                // Create a MediaClip from the file
                var clip = await MediaClip.CreateFromFileAsync(videoFile);

                // Set the End Trim slider's maximum value so that the user can trim from the end
                // You can also do this from the start
                EndTrimSlider.Maximum = clip.OriginalDuration.TotalMilliseconds;

                // Create a MediaComposition containing the clip and set it on the MediaElement.
                composition = new MediaComposition();
                composition.Clips.Add(clip);

                // start the MediaElement at the beginning
                EditorMediaElement.Position = TimeSpan.Zero;

                // Create the media source and assign it to the media player
                mediaStreamSource = composition.GeneratePreviewMediaStreamSource((int)EditorMediaElement.ActualWidth, (int)EditorMediaElement.ActualHeight);

                // Set the MediaElement's source
                EditorMediaElement.SetMediaStreamSource(mediaStreamSource);

                TrimClipButton.IsEnabled = true;
            }
        }
Пример #14
0
        public async Task CS_WP_MC_PreviewTranscode(EffectType effectType)
        {
            StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/Car.mp4"));

            StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("CS_WP_MC_PreviewTranscode_" + effectType + ".mp4", CreationCollisionOption.ReplaceExisting);

            var definition = await Utils.CreateEffectDefinitionAsync(effectType);

            var clip = await MediaClip.CreateFromFileAsync(source);

            clip.VideoEffectDefinitions.Add(definition);

            var composition = new MediaComposition();

            composition.Clips.Add(clip);

            MediaStreamSource sourceStreamSource = composition.GenerateMediaStreamSource();

            using (IRandomAccessStream destinationStream = await destination.OpenAsync(FileAccessMode.ReadWrite))
            {
                var transcoder = new MediaTranscoder();
                var transcode  = await transcoder.PrepareMediaStreamSourceTranscodeAsync(sourceStreamSource, destinationStream, MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga));

                await transcode.TranscodeAsync();
            }
        }
Пример #15
0
        private async void  Button_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
            picker.FileTypeFilter.Add(".mp4");
            pickedFile = await picker.PickSingleFileAsync();

            var storageItemAccessList = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList;

            storageItemAccessList.Add(pickedFile);

            var clip = await MediaClip.CreateFromFileAsync(pickedFile);

            if (pickedFile == null)
            {
                return;
            }


            else
            {
                composition = new MediaComposition();
                composition.Clips.Add(clip);
                mediaElement1.Position = TimeSpan.Zero;
                mediaStreamSource      = composition.GeneratePreviewMediaStreamSource(500, 200);
                mediaElement1.SetMediaStreamSource(mediaStreamSource);
                import_btn.IsEnabled = false;
            }
        }
        private async Task StartVideoAsync(StorageFile file)
        {
            try
            {
                if (this.videoPlayer.CurrentState == MediaElementState.Playing)
                {
                    this.videoPlayer.Stop();
                }

                FrameRelayVideoEffect.ResetState();

                this.currentVideoId = Guid.NewGuid();
                await this.ResetStateAsync();

                MediaClip clip = await MediaClip.CreateFromFileAsync(file);

                clip.VideoEffectDefinitions.Add(new VideoEffectDefinition(typeof(FrameRelayVideoEffect).FullName));

                MediaComposition compositor = new MediaComposition();
                compositor.Clips.Add(clip);

                this.videoPlayer.SetMediaStreamSource(compositor.GenerateMediaStreamSource());
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Error starting playback.");
            }
        }
Пример #17
0
        public async Task SetupMediaComposition(MediaComposition mediaComposition)
        {
            var captureVideoFile = await StorageFile.GetFileFromPathAsync(_captureVideoFilePath);

            var clip = await MediaClip.CreateFromFileAsync(captureVideoFile);

            mediaComposition.Clips.Add(clip);
        }
Пример #18
0
        private async Task <Dictionary <TimeSpan, Face[]> > DetectFace_Video(StorageFile fileData)
        {
            // Process configs
            const int frameJumpSize = 15;
            const int frameQuota    = 20;
            const int frameTimeout  = 60_000;

            // Video
            var videoProperties = await fileData.Properties.GetVideoPropertiesAsync();

            var videoTime  = TimeSpan.FromSeconds(0);
            var videoFrame = 0;

            // DetectedFaces
            var detectedFaces = new Dictionary <TimeSpan, Face[]>();

            // Process every frame
            while (videoTime < videoProperties.Duration)
            {
                // Frame cut
                var mediaClip = await MediaClip.CreateFromFileAsync(fileData);

                var mediaComposition = new MediaComposition();
                mediaComposition.Clips.Add(mediaClip);
                var frame = await mediaComposition.GetThumbnailAsync(
                    videoTime,
                    0,
                    0,
                    VideoFramePrecision.NearestFrame
                    );

                // Stream conversion
                var randomAccessStream = new InMemoryRandomAccessStream();
                await RandomAccessStream.CopyAsync(frame, randomAccessStream);

                randomAccessStream.Seek(0);

                // Process and add image
                var detectedFace = await DetectFace_Image(randomAccessStream.AsStreamForRead());

                if (detectedFace != null)
                {
                    detectedFaces.Add(videoTime, detectedFace);
                }

                // Quota overflow
                if (videoFrame != 0 && videoFrame % frameQuota == 0)
                {
                    await Task.Delay(frameTimeout);
                }

                // Frame and time incrementation
                videoTime  += TimeSpan.FromSeconds(frameJumpSize);
                videoFrame += 1;
            }

            return(detectedFaces);
        }
Пример #19
0
        public async Task <IInputStream> GetThumbnailAsync(StorageFile file, int milliseconds)
        {
            var mediaClip = await MediaClip.CreateFromFileAsync(file);

            var mediaComposition = new MediaComposition();

            mediaComposition.Clips.Add(mediaClip);
            return(await mediaComposition.GetThumbnailAsync(TimeSpan.FromMilliseconds(milliseconds), 200, 200, VideoFramePrecision.NearestFrame));
        }
Пример #20
0
        /**
         * 動画ファイルをロードして、フレームサムネイルを抽出する。
         */
        private async void LoadMediaSource(StorageFile source)
        {
            Ready = false;

            //
            Error.Reset();
            mPlayer.Source = null;
            mPreviewing    = false;
            mTrimmingSlider.Reset();
            mFrameListView.Reset();
            mExtractor.Cancel();
            mFrameListView.ShowCurrentTick = false;

            mComposition.Clips.Clear();
            if (null != source)
            {
                mOriginalSource = MediaSource.CreateFromStorageFile(source);
                var loader = await WvvMediaLoader.LoadAsync(mPlayer, mOriginalSource, this);

                if (loader.Opened)
                {
                    TotalRange = loader.TotalRange;
                    VideoSize  = loader.VideoSize;

                    try
                    {
                        var clip = await MediaClip.CreateFromFileAsync(source);

                        mComposition.Clips.Add(clip.Clone());
                        Ready = true;
                        await mExtractor.ExtractAsync(clip, (s, i, img) =>
                        {
                            mFrameListView.Frames[i] = img;
                        },
                                                      (s, img) =>
                        {
                            mFrameListView.FrameListHeight = mExtractor.ThumbnailHeight;
                            for (int i = 0; i < ThumbnailCount; i++)
                            {
                                mFrameListView.Frames.Add(img);
                            }
                            mFrameListView.ShowCurrentTick = true;
                        });
                    }
                    catch (Exception e)
                    {
                        CmLog.error(e, "WvvTrimmingView.LoadMediaSource: Error");
                        Error.SetError(e);
                    }
                }
                else // not opened.
                {
                    Error.CopyFrom(loader.Error);
                }
            }
        }
Пример #21
0
        //public bool IsCropEnabled
        //{
        //    get { return this.Cropper.IsCropEnabled; }
        //    set { this.Cropper.IsCropEnabled = value; }
        //}

        //public Rect CropRectangle
        //{
        //    get { return this.Cropper.CropRectangle; }
        //}

        private async void InitializeVideo(StorageFile file)
        {
            Media.Source = MediaSource.CreateFromStorageFile(file);
            Media.MediaPlayer.AutoPlay         = true;
            Media.MediaPlayer.IsMuted          = true;
            Media.MediaPlayer.IsLoopingEnabled = true;
            Media.MediaPlayer.PlaybackSession.PositionChanged += MediaPlayer_PositionChanged;

            var clip = await MediaClip.CreateFromFileAsync(file);

            var composition = new MediaComposition();

            composition.Clips.Add(clip);

            var props = clip.GetVideoEncodingProperties();

            double ratioX = (double)40 / props.Width;
            double ratioY = (double)40 / props.Height;
            double ratio  = Math.Max(ratioY, ratioY);

            var width  = (int)(props.Width * ratio);
            var height = (int)(props.Height * ratio);

            var count = Math.Ceiling(280d / width);

            var times = new List <TimeSpan>();

            for (int i = 0; i < count; i++)
            {
                times.Add(TimeSpan.FromMilliseconds(clip.OriginalDuration.TotalMilliseconds / count * i)); // TimeSpan.FromMilliseconds for older Frameworks (instead of Divide)
            }

            TrimThumbnails.Children.Clear();
#if MOBILE
            var lumiaScaleFactor = 4; // prevents Catastrophic failure on Lumia 640 & probably others
            var thumbnails       = await composition.GetThumbnailsAsync(times, width *lumiaScaleFactor, height *lumiaScaleFactor, VideoFramePrecision.NearestKeyFrame);
#else
            var thumbnails = await composition.GetThumbnailsAsync(times, width, height, VideoFramePrecision.NearestKeyFrame);
#endif
            foreach (var thumb in thumbnails)
            {
                var bitmap = new BitmapImage();
                await bitmap.SetSourceAsync(thumb);

                var image = new Image();
                image.Width   = width;
                image.Height  = height;
                image.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
                image.Source  = bitmap;

                TrimThumbnails.Children.Add(image);
            }

            TrimRange.SetOriginalDuration(clip.OriginalDuration);
        }
Пример #22
0
        public async Task <IFrameSource> Encode(StorageFile source)
        {
            MediaClip clip = await MediaClip.CreateFromFileAsync(source);

            var props             = clip.GetVideoEncodingProperties();
            var frameMilliseconts = 1000.0f / ((float)props.FrameRate.Numerator / (float)props.FrameRate.Denominator);
            var frameCount        = (int)(clip.OriginalDuration.TotalMilliseconds / frameMilliseconts);

            var fps = MediaHelper.MillisecondsToFPS((long)frameMilliseconts);

            var frameSource = new FrameSet(fps, (int)props.Width, (int)props.Height);

            TimeSpan frameDuration  = TimeSpan.FromMilliseconds((int)fps);
            TimeSpan frameStartTime = new TimeSpan();

            MediaComposition composition = new MediaComposition();

            composition.Clips.Add(clip);

            for (int idx = 0; idx < frameCount; idx++)
            {
                var time = TimeSpan.FromMilliseconds(idx * frameMilliseconts);

                var frame = await composition.GetThumbnailAsync(
                    time,
                    (int)props.Width,
                    (int)props.Height,
                    VideoFramePrecision.NearestFrame
                    );

                using (var stream = new InMemoryRandomAccessStream())
                {
                    await RandomAccessStream.CopyAsync(frame, stream);

                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    stream.Seek(0);

                    SoftwareBitmap bitmap = SoftwareBitmap.Convert(
                        await decoder.GetSoftwareBitmapAsync(),
                        BitmapPixelFormat.Rgba16,
                        BitmapAlphaMode.Premultiplied);

                    frameSource.AddFrame(new Frame(bitmap)
                    {
                        Duration = frameDuration, StartTime = frameStartTime
                    });
                    frameStartTime += frameDuration;
                }
            }

            return(frameSource);
        }
Пример #23
0
        async void OnLoaded(object sender, RoutedEventArgs e)
        {
            this.mediaElement.Visibility = Visibility.Collapsed;
            this.progressInfo.Visibility = Visibility.Visible;
            this.progressRing.IsActive   = true;
            this.progressText.Text       = "Downloading video...";

            var thumbnailFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Logo.scale-100.png"));

            var thumbnail = RandomAccessStreamReference.CreateFromFile(thumbnailFile);

            var url = "http://video.ch9.ms/ch9/4597/8db5a656-b173-4897-b2aa-e2075fb24597/windows10recap.mp4";

            // TODO: replace TemporaryFolder and HttpClient with StorageFile.CreateStreamedFileFromUriAsync once TH:2458060 is fixed
            //var file = await StorageFile.CreateStreamedFileFromUriAsync(
            //    "windows10recap.mp4",
            //    new Uri(url),
            //    thumbnail);

            var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("windows10recap.mp4", CreationCollisionOption.ReplaceExisting);

            using (var httpClient = new HttpClient())
            {
                byte[] videoData = await httpClient.GetByteArrayAsync(url);

                using (var writer = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await writer.WriteAsync(videoData.AsBuffer());
                }
            }

            this.progressText.Text = "Creating clip...";
            var clip = await MediaClip.CreateFromFileAsync(file);

            clip.VideoEffectDefinitions.Add(new VideoEffectDefinition(typeof(ExampleVideoEffect).FullName));

            var composition = new MediaComposition();

            composition.Clips.Add(clip);

            if (ThumbnailGenerator.IsDrawingThumbnail)
            {
                this.thumbnail = await composition.GetThumbnailAsync(TimeSpan.FromSeconds(10), 1280, 720, VideoFramePrecision.NearestFrame);
            }

            mediaElement.SetMediaStreamSource(composition.GenerateMediaStreamSource());
            mediaElement.IsLooping = true;

            this.mediaElement.Visibility = Visibility.Visible;
            this.progressInfo.Visibility = Visibility.Collapsed;
            this.progressRing.IsActive   = false;
        }
Пример #24
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            destination = await ApplicationData.Current.LocalFolder.CreateFileAsync("myfile1", CreationCollisionOption.ReplaceExisting);

            var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

            openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
            openPicker.FileTypeFilter.Add(".wmv");
            openPicker.FileTypeFilter.Add(".mp4");
            openPicker.FileTypeFilter.Add(".flv");
            openPicker.FileTypeFilter.Add(".3gp");
            openPicker.FileTypeFilter.Add(".avi");
            openPicker.FileTypeFilter.Add(".mkv");
            source = await openPicker.PickSingleFileAsync();

            //获取视频信息
            if (source != null)
            {
                var clip = await MediaClip.CreateFromFileAsync(source);

                property = clip.GetVideoEncodingProperties();
                string encodeInfo = property.Subtype;
                Source_height = property.Height;
                Source_width  = property.Width;

                Source_frameRate = property.FrameRate.Numerator;
                dataRate         = property.Bitrate;
            }
            //获取声频信息
            if (source != null)
            {
                AudioGraphSettings     settings     = new AudioGraphSettings(Windows.Media.Render.AudioRenderCategory.Media);
                CreateAudioGraphResult createResult = await AudioGraph.CreateAsync(settings);

                if (createResult.Status != AudioGraphCreationStatus.Success)
                {
                    return;
                }
                AudioGraph audioGraph = createResult.Graph;
                CreateAudioFileInputNodeResult result = await audioGraph.CreateFileInputNodeAsync(source);

                if (result.Status != AudioFileNodeCreationStatus.Success)
                {
                    return;
                }
                AudioFileInputNode      fileInputNode = result.FileInputNode;
                AudioEncodingProperties property      = fileInputNode.EncodingProperties;
                //Get encode property
                string subTitles = property.Subtype;
                SampleRate = property.SampleRate;
            }
        }
Пример #25
0
        public async Task CS_WP_MC_LumiaCropSquare()
        {
            StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/Car.mp4"));

            StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("CS_W_MT_CropSquare.mp4", CreationCollisionOption.ReplaceExisting);

            // Select the largest centered square area in the input video
            var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(source);

            uint inputWidth   = encodingProfile.Video.Width;
            uint inputHeight  = encodingProfile.Video.Height;
            uint outputLength = Math.Min(inputWidth, inputHeight);
            Rect cropArea     = new Rect(
                (float)((inputWidth - outputLength) / 2),
                (float)((inputHeight - outputLength) / 2),
                (float)outputLength,
                (float)outputLength
                );

            encodingProfile.Video.Width  = outputLength;
            encodingProfile.Video.Height = outputLength;

            var definition = new LumiaEffectDefinition(new FilterChainFactory(() =>
            {
                var filters = new List <IFilter>();
                filters.Add(new CropFilter(cropArea));
                return(filters);
            }));

            definition.InputWidth   = inputWidth;
            definition.InputHeight  = inputHeight;
            definition.OutputWidth  = outputLength;
            definition.OutputHeight = outputLength;

            var clip = await MediaClip.CreateFromFileAsync(source);

            clip.VideoEffectDefinitions.Add(definition);

            var composition = new MediaComposition();

            composition.Clips.Add(clip);

            MediaStreamSource sourceStreamSource = composition.GenerateMediaStreamSource();

            using (IRandomAccessStream destinationStream = await destination.OpenAsync(FileAccessMode.ReadWrite))
            {
                var transcoder = new MediaTranscoder();
                var transcode  = await transcoder.PrepareMediaStreamSourceTranscodeAsync(sourceStreamSource, destinationStream, MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga));

                await transcode.TranscodeAsync();
            }
        }
Пример #26
0
        private async void InitializeVideo(StorageFile file)
        {
            Media.Source = MediaSource.CreateFromStorageFile(file);
            Media.MediaPlayer.AutoPlay         = true;
            Media.MediaPlayer.IsMuted          = true;
            Media.MediaPlayer.IsLoopingEnabled = true;
            Media.MediaPlayer.PlaybackSession.PositionChanged += MediaPlayer_PositionChanged;

            var clip = await MediaClip.CreateFromFileAsync(file);

            var composition = new MediaComposition();

            composition.Clips.Add(clip);

            var props = clip.GetVideoEncodingProperties();

            double ratioX = (double)40 / props.Width;
            double ratioY = (double)40 / props.Height;
            double ratio  = Math.Max(ratioY, ratioY);

            var width  = (int)(props.Width * ratio);
            var height = (int)(props.Height * ratio);

            var count = Math.Ceiling(296d / width);

            var times = new List <TimeSpan>();

            for (int i = 0; i < count; i++)
            {
                times.Add(clip.OriginalDuration / count * i);
            }

            TrimThumbnails.Children.Clear();

            var thumbnails = await composition.GetThumbnailsAsync(times, width, height, VideoFramePrecision.NearestKeyFrame);

            foreach (var thumb in thumbnails)
            {
                var bitmap = new BitmapImage();
                await bitmap.SetSourceAsync(thumb);

                var image = new Image();
                image.Width   = width;
                image.Height  = height;
                image.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
                image.Source  = bitmap;

                TrimThumbnails.Children.Add(image);
            }

            TrimRange.SetOriginalDuration(clip.OriginalDuration);
        }
Пример #27
0
        private async Task <ImageStream> GetImageStream(TimeSpan timeOfFrame, StorageFile pickedFile)
        {
            var clip = await MediaClip.CreateFromFileAsync(pickedFile);

            var composition = new MediaComposition();

            composition.Clips.Add(clip);

            var imageStream = await composition.GetThumbnailAsync(timeOfFrame, (int)resolution.Width, (int)resolution.Height,
                                                                  VideoFramePrecision.NearestFrame);

            return(imageStream);
        }
Пример #28
0
        private async void BaseVideo_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker();

            picker.FileTypeFilter.Add(".mp4");
            picker.FileTypeFilter.Add(".mov");
            var file = await picker.PickSingleFileAsync();

            var clip = await MediaClip.CreateFromFileAsync(file);

            _composition.Clips.Add(clip);

            SetupMediaStreamSource();
        }
Пример #29
0
        public async Task <ImageStream> ExtractSingleFrameStreamAsync(StorageFile source, TimeSpan position)
        {
            try
            {
                var clip = await MediaClip.CreateFromFileAsync(source);

                return(await ExtractSingleFrameStreamAsync(clip, position));
            }
            catch (Exception e)
            {
                CmLog.error("WvvFrameExtractor2.ExtractSingleFrameStreamAsync(StorageFile)", e);
                return(null);
            }
        }
Пример #30
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            CameraCaptureUI video = new CameraCaptureUI();

            video.VideoSettings.Format        = CameraCaptureUIVideoFormat.Mp4;
            video.VideoSettings.MaxResolution = CameraCaptureUIMaxVideoResolution.HighDefinition;
            storeFile = await video.CaptureFileAsync(CameraCaptureUIMode.Video);

            if (storeFile != null)
            {
                stream = await storeFile.OpenAsync(FileAccessMode.Read);

                MediaClip media = await MediaClip.CreateFromFileAsync(storeFile);

                MediaComposition mComposition = new MediaComposition();
                mComposition.Clips.Add(media);
                MediaStreamSource source = mComposition.GeneratePreviewMediaStreamSource((int)demoVideo.ActualWidth, (int)demoVideo.ActualHeight);
                demoVideo.SetMediaStreamSource(source);


                DateTime dt    = DateTime.Now;
                string   dtstr = dt.ToString("ddMyyyy");

                string filename = "videorecordedat" + dtstr;


                //FileSavePicker save = new FileSavePicker();
                //save.FileTypeChoices.Add("Video", new List<string>() { ".mp4", ".wmv" });
                //save.DefaultFileExtension = ".mp4";
                //save.SuggestedFileName = "video"+filename;
                //save.SuggestedStartLocation = PickerLocationId.VideosLibrary;
                //save.SuggestedSaveFile = storeFile;
                //var s = await save.PickSaveFileAsync();

                using (var reader = new DataReader(stream.GetInputStreamAt(0)))
                {
                    await reader.LoadAsync((uint)stream.Size);

                    byte[] buffer = new byte[(int)stream.Size];
                    reader.ReadBytes(buffer);
                    await FileIO.WriteBytesAsync(storeFile, buffer);
                    await Upload(storeFile, buffer);
                }



                this.Frame.Navigate(typeof(BlankPage3));
            }
        }