【问题标题】:Combining MediaTimeline with animation in Storyboard programmatically以编程方式将 MediaTimeline 与 Storyboard 中的动画相结合
【发布时间】:2012-01-24 04:56:46
【问题描述】:

我正在尝试在 Storyboard 中使用 MediaTimeline 和 DoubleAnimation 来播放带有动画的音频。一切都是在没有 XAML 的 C# 中实现的。在下面的代码中调用 Storyboard.Begin 之后没有任何反应,并且没有引发异常。 mediaElement 的 HasAudio 属性为 false 并且永远不会调用 MediaElement 的 MediaOpened 事件。似乎 mediaElement 无法加载音频文件。我不知道是 MediaElement 还是 MediaTimeline 负责加载音频。没有 MediaTimeline,DoubleAnimation 也能正常工作。我在这里错过了什么?

private void SetStoryboard(double beginLeft, double endLeft, TimeSpan duration)
{
        mediaElement = new MediaElement();
        mediaElement.LoadedBehavior = MediaState.Manual;
        mediaElement.ScrubbingEnabled = true;
        mediaElement.MediaOpened += new RoutedEventHandler(MediaElement_MediaOpened);

        mediaTimeline = new MediaTimeline();
        mediaTimeline.Duration = new Duration(duration);
        mediaTimeline.Source = new Uri(musicFilePath);
        mediaTimeline.FillBehavior = FillBehavior.Stop;
        Storyboard.SetTarget(mediaTimeline, mediaElement);

        anim = new DoubleAnimation();
        anim.From = beginLeft;
        anim.To = endLeft;
        anim.Duration = new Duration(duration);
        anim.FillBehavior = FillBehavior.Stop;
        Storyboard.SetTarget(anim, slider);
        Storyboard.SetTargetProperty(anim, new PropertyPath(Canvas.LeftProperty));

        storyboard = new Storyboard();
        storyboard.SlipBehavior = SlipBehavior.Slip;
        storyboard.Children.Add(mediaTimeline);
        storyboard.Children.Add(anim);

        storyboard.Begin(this, true);
}

【问题讨论】:

    标签: wpf animation storyboard mediaelement


    【解决方案1】:

    您的 MediaElement 不是 VisualTree 的一部分。您正在构建它,但由于它没有分配给可视化树,因此布局系统将永远不会使用它。

    您可以通过将其添加到有效的容器元素中来将其添加到代码隐藏中。 例如

    XAML:

    <Grid x:Name="parentGrid">
    

    代码隐藏:

    var mediaElement = new MediaElement();
    parentGrid.Children.Add(mediaElement);
    

    或者您可以将 MediaElement 放置在您的页面/窗口上,删除构建 MediaElement 的行 (.. = new MediaElement),然后通过代码隐藏访问它:

    XAML:

    <MediaElement x:Name="mediaElement" Width="200" Height="100"/>
    

    【讨论】:

    • 谢谢,现在可以使用了。我不明白为什么需要将其添加到 VisualTree。如果它是一个视频是有道理的,但它也可以用来播放音频,就像我的例子一样。
    • @Alp,因为MediaElement 在您需要一些视觉表示时使用。在其他情况下,通常使用MediaPlayerSoundPlayer
    • 但是我不能使用 MediaPlayer 或 SoundPlayer,因为当我将 MediaTimeline 定位到 MediaPlayer 时,我得到以下 InvalidOperationEception“MediaTimeline 必须附加到 MediaElement,或者具有引用 MediaElement 的 TargetName”。跨度>
    猜你喜欢
    • 2013-05-02
    • 1970-01-01
    • 2018-03-15
    • 2017-10-21
    • 1970-01-01
    • 2011-12-24
    • 2019-07-24
    • 2014-05-04
    • 1970-01-01
    相关资源
    最近更新 更多