关闭Window后MediaTimeline继续播放

时间:2014-11-29 03:13:40

标签: c# wpf

我有这段代码:

        MediaTimeline timeline = new MediaTimeline(new Uri(@path, UriKind.Relative));
        MediaClock clock = timeline.CreateClock();
        System.Windows.Media.MediaPlayer player = new System.Windows.Media.MediaPlayer();
        player.Clock = clock;
        VideoDrawing drawing = new VideoDrawing();
        drawing.Rect = new Rect(0, 0, 300, 200);
        drawing.Player = player;
        DrawingBrush brush = new DrawingBrush(drawing);
        New_WEBMPlayer_Wnd.Background = brush;

使用新窗口运行以播放该特定文件...问题是如果我关闭窗口,声音会继续播放。所以我猜视频也是如此。如何在关闭后停止?

1 个答案:

答案 0 :(得分:0)

您需要通过clock停止播放器,因为播放器现在由其Clock控制。如果您直接停止播放(不是通过Clock),您将获得InvalidOperationException

  

PresentationCore.dll中出现未处理的“System.InvalidOperationException”类型异常

     

附加信息:将时钟分配给媒体播放器时无法执行此操作。

首先,制作时钟controllable

MediaClock clock = timeline.CreateClock(true) as MediaClock;

你就这样停止了玩家,

if (clock.CurrentState != ClockState.Stopped)
{
    clock.Controller.Stop();
}

总之,工作代码看起来像这样

MediaTimeline timeline = new MediaTimeline(new Uri(@path, UriKind.Relative));
MediaClock clock = timeline.CreateClock(true) as MediaClock; //make the clock controllable
MediaPlayer player = new MediaPlayer();
player.Clock = clock;
VideoDrawing drawing = new VideoDrawing();
drawing.Rect = new Rect(0, 0, 300, 200);
drawing.Player = player;
DrawingBrush brush = new DrawingBrush(drawing);
New_WEBMPlayer_Wnd.Background = brush;

//stop the clock when player window is closed
New_WEBMPlayer_Wnd.Closed += (s, e) =>
{
    if (clock.CurrentState != ClockState.Stopped)
    {
        clock.Controller.Stop();
    }
};