将预加载的MediaClip添加到MediaComposition.Clips会引发System.ArgumentException

时间:2016-09-18 10:46:36

标签: c# windows-runtime uwp

异常消息:

  

抛出异常:' System.ArgumentException'在mscorlib.ni.dll中

     

WinRT信息:元素已在使用中

     

参数不正确。

代码:

composition = await MediaComposition.LoadAsync(timelineCMPOutputFile);
composition2 = await MediaComposition.LoadAsync(timelineCMPOutputFile2);

//TODO: Warn user to select the oldest first.
try
{
    for (int i = 0; i < composition2.Clips.Count; i++)
    {
         composition.Clips.Add(composition2.Clips[i]); // Exception throws here.
    }
}
catch(Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
}

var action = composition.SaveAsync(timelineCMPOutputFile);

基本上我尝试做的是将MediaComposition.Clips合并到一个实例中。

1 个答案:

答案 0 :(得分:1)

合成内容保存为XML文件,其中包含有关合成的元数据,例如源媒体文件,剪辑排列,叠加层以及应用于合成的效果,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<Composition>
  <Clips>
    <MediaClip ExpectedOriginalDuration="5816533125" Path="C:\Users\username\AppData\Local\Packages\Microsoft.SDKSamples.MediaEditingSample.CS_8wekyb3d8bbwe\LocalState\temp.mp4"/>
  </Clips>
</Composition>

我们从XML文件获取的剪辑信息不是媒体源的剪辑,它们是定义原始源路径的元数据。似乎只有从媒体文件创建的剪辑才能成功添加到合成中。所以解决方案是通过MediaComposition.RenderToFileAsync将第二个加载的合成渲染到媒体文件,然后从文件中创建一个新剪辑。最后,将新剪辑添加到第一个加载的合成中以完成合并。更新后的代码如下。

 StorageFile timelineCMPOutputFile = await ApplicationData.Current.LocalFolder.GetFileAsync("timelineCMPOutputFile");
 StorageFile timelineCMPOutputFile2 = await ApplicationData.Current.LocalFolder.GetFileAsync("timelineCMPOutputFile2");
 var composition = await MediaComposition.LoadAsync(timelineCMPOutputFile);
 var composition2 = await MediaComposition.LoadAsync(timelineCMPOutputFile2);
 //TODO: Warn user to select the oldest first.
 try
 {
     await composition2.RenderToFileAsync(await ApplicationData.Current.LocalFolder.CreateFileAsync("temp.mp4", CreationCollisionOption.ReplaceExisting));
     StorageFile tempfile = await ApplicationData.Current.LocalFolder.GetFileAsync("temp.mp4");
     MediaClip firstClip = await MediaClip.CreateFromFileAsync(tempfile);            
     composition.Clips.Add(firstClip); /// Exception throws here.
 }
 catch (Exception ex)
 {
     System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
 }

 var action = composition.SaveAsync(timelineCMPOutputFile);

 // Combine two video files together into one