如何在UWP中创建带有覆盖的视频?

时间:2018-10-15 11:32:00

标签: c# .net uwp windows-10-universal mediaelement

我正在使用MediaComposition来创建编辑过的视频。

组成的视频将是:

  • 一个视频剪辑
  • 应在其顶部显示的一组图像(重叠帧)。

结果应如下所示:https://www.youtube.com/watch?v=cFEkkQIYGBc

我当前的代码如下所示。每个帧都是覆盖图像的抽象。我称它为框架

private async Task ExportFrames(IEnumerable<OverlayFrame> frames, IStorageFile inputFile,
    IStorageFile outputFile)
{
    var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Test", CreationCollisionOption.ReplaceExisting);
    var composition = new MediaComposition();

    foreach (var frame in frames)
    {
        var render = new RenderTargetBitmap();
        control.DataContext = convertFunc(frame.Status);

        await render.RenderAsync(control);
        var pixel = await render.GetPixelsAsync();
        var file = await folder.CreateFileAsync("overlay.png", CreationCollisionOption.GenerateUniqueName);
        using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

            encoder.SetPixelData(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Ignore,
                (uint)render.PixelWidth,
                (uint)render.PixelHeight,
                logicalDpi,
                logicalDpi,
                pixel.ToArray());

            await encoder.FlushAsync();
            stream.Dispose();
            var clip = await MediaClip.CreateFromImageFileAsync(file, frame.Duration);
            AddOverlay(composition, clip, 0, 0, control.ActualWidth, control.ActualHeight);
        }                
    }

    var originalVideo = await MediaClip.CreateFromFileAsync(inputFile);
    composition.Clips.Add(originalVideo);

    await composition.RenderToFileAsync(outputFile, MediaTrimmingPreference.Precise);
    await folder.DeleteAsync();
}

private void AddOverlay(MediaComposition composition, MediaClip overlayMediaClip, double left, double top, double width, double height)
{
    var overlayPosition = new Rect(left, top, width, height);

    var mediaOverlay = new MediaOverlay(overlayMediaClip)
    {
        Position = overlayPosition,                 
    };

    var mediaOverlayLayer = new MediaOverlayLayer();
    mediaOverlayLayer.Overlays.Add(mediaOverlay);

    composition.OverlayLayers.Add(mediaOverlayLayer);
}

foreach中,我生成一个与覆盖信息相对应的png文件。它是通过UI控件中的RenderTargetBitmap生成的。

在foreach循环之后,我添加了原始视频(inputFile

问题在于生成的视频仅显示原始视频。没有覆盖。

我在做什么错了?

0 个答案:

没有答案