我正在使用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对象并再次创建的情况。记忆力再次消耗殆尽。
任何建议都将不胜感激!
答案 0 :(得分:0)
我的建议是做以下事情:
private void VideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
// choose the next media file
...
//make the following explicitly
MediaPlayer.Stop();
MediaPlayer.Source = null;
model.OnPropertyChanged("MySource");
MediaPlayer.Play();
}
答案 1 :(得分:0)
尝试在XAML中指定MediaElement UnloadingBehavior="Close"
属性。
根据MSDN MediaState::Close
表示
释放所有媒体资源(包括视频内存)。