Code Bye

WPF MediaElement不能暂停,这是怎么回事?请高手指点

XAML文件里定义了MediaElement控件,LoadedBehavior=”Manual” UnloadedBehavior=”Pause”;
<MediaElement x:Name="mySoundPlayer" DataContext="{Binding}" LoadedBehavior="Manual" UnloadedBehavior="Pause" >
            <MediaElement.Triggers>
                <EventTrigger RoutedEvent="MediaElement.Loaded">
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard>
                                <!-- The MediaTimeline has a RepeatBehavior="Forever" which makes the media play
                     over and over indefinitely.-->
                                <MediaTimeline Source="{Binding BgMusicPath}" Storyboard.TargetName="mySoundPlayer"  
                 RepeatBehavior="Forever" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>
            </MediaElement.Triggers>
        </MediaElement>

也定义了获取文件的方法

   private void playSound()
        {
            BgMusic bm = new BgMusic();
            bm.BgMusicPath = cBackMusic ;
            mySoundPlayer.DataContext = bm;
        }
[code=csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LotteryGo
{
    public class BgMusic
    {
        public string BgMusicPath { get; set; }
    }
}

在Load里写了开始播放的语句,播放的测试是正常的。但是,下面的Button过程就来问题了:无法暂停,这个按钮直接没反应了。

 if (_isPlaying)
            {
                mySoundPlayer.Pause();
                _isPlaying = false;
            }
            else
            {
                mySoundPlayer.Play();
                _isPlaying = true;
            }
解决方案

20

你应该把触发器那一段去掉,在Loaded事件里面用代码开始播放,而不是用动画播放。
MediaElement 可以在两个不同的模式中使用,具体取决于驱动控件的模式是独立模式还是时钟模式。当在独立模式中使用时,MediaElement 与图像相似,并且可以直接指定 Source URI。在时钟模式中,MediaElement 可以看作是动画目标,因此它在计时树中具有相应的 Timeline 和 Clock 项。你是在时钟模式下播放的,因此播放完全是按照动画的Timeline 控制。
你应该在独立模式下播放,就是删掉动画那部分,将LoadedBehavior=”Manual”,这样就能手动控制播放、暂停和停止了。

20

引用 1 楼 Libby1984 的回复:

你应该把触发器那一段去掉,在Loaded事件里面用代码开始播放,而不是用动画播放。
MediaElement 可以在两个不同的模式中使用,具体取决于驱动控件的模式是独立模式还是时钟模式。当在独立模式中使用时,MediaElement 与图像相似,并且可以直接指定 Source URI。在时钟模式中,MediaElement 可以看作是动画目标,因此它在计时树中具有相应的 Timeline 和 Clock 项。你是在时钟模式下播放的,因此播放完全是按照动画的Timeline 控制。
你应该在独立模式下播放,就是删掉动画那部分,将LoadedBehavior=”Manual”,这样就能手动控制播放、暂停和停止了。

<MediaElement x:Name=”mySoundPlayer” DataContext=”{Binding}” LoadedBehavior=”Manual” UnloadedBehavior=”Pause”  Source=”{Binding BgMusicPath}” Loaded=”MediaElement_Loaded”>


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明WPF MediaElement不能暂停,这是怎么回事?请高手指点