我正在使用 MediaElement 长时间循环显示视频剪辑。一段时间后(Win 7/4 GB RAM 为数小时),程序崩溃,但类型为“内存不足”。我监控了使用 Process Explorer-Sysinternals 时使用的内存,并使用 System.Diagnostics.Process 方法记录了它。两种方式都显示已用内存逐渐增加。
这是代码:
XAML:
<Grid Name="GridTest">
<MediaElement x:Name="MediaPlayer"
LoadedBehavior="Manual"
MediaEnded="VideoControl_MediaEnded"
MediaOpened="MediaPlayer_MediaOpened"
Source="{Binding Mode=OneWay,
Path=MySource}" />
</Grid>
.cs:
public partial class MainWindow : Window
{
public MainViewModel model = new MainViewModel();
public MainWindow()
{
InitializeComponent();
this.GridTest.DataContext = model;
// fill in model.MediaFilesUris:
...
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// choose the next media file
...
MediaPlayer.Play();
}
private void VideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
// choose the next media file
...
model.OnPropertyChanged("MySource");
MediaPlayer.Play();
}
}
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public Uri[] MediaFilesUris = null;
public int crn = 0;
public Uri MySource { get { if (MediaFilesUris != null && MediaFilesUris.Count()>0) return MediaFilesUris[crn]; else return null; } }
}
我还测试了 MediaElement 对象动态创建、在几个剪辑后被销毁(以及所有取消订阅事件等)并再次创建的情况。内存消耗再次增加。
如有任何建议,我们将不胜感激!
最佳答案
尝试在 XAML 中指定 MediaElement UnloadingBehavior="Close"
属性。
根据 MSDN MediaState::Close
表明
All media resources are released (including video memory).
关于c# - 如何释放 MediaElement 使用的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35873942/