如何向 UWP 故事板动画添加声音

How do I add sound to UWP storyboard animation

我正在尝试用我的动画播放声音。我已经有了一个使用 StoryBoard 和 DoubleAnimation 的工作动画。有谁知道如何添加声音吗?

Microsoft 文档建议使用 MediaTimeline class:

There are two ways to associate a Timeline to a MediaElement using a MediaTimeline:

  1. Inside of a Storyboard, when a MediaTimeline is targets [sic] a MediaElement, a MediaClock will be created and assigned to the MediaElement’s associated player. See How to: Control a MediaElement by Using a Storyboard for an example;

  2. By explicitly creating a MediaClock from a MediaTimeline and assigning it to a MediaElement.

Stack Overflow 答案也建议使用 MediaTimeline。

问题是 UWP 的 Windows.Media 命名空间中不存在 MediaTimeline class。

我的动画代码是这样的:

DoubleAnimation animX = new DoubleAnimation();
DoubleAnimation animY = new DoubleAnimation();

animX.Duration = TimeSpan.FromMilliseconds(600);
animY.Duration = TimeSpan.FromMilliseconds(800);
animX.From = pStart.X;
animX.To = pEnd.X;
animY.From = pStart.Y;
animY.To = pEnd.Y;

Storyboard StarStoryboard = new Storyboard();

Storyboard.SetTarget(animX, this.MyImage);
Storyboard.SetTargetProperty(animX, "(Canvas.Left)");

Storyboard.SetTarget(animY, this.MyImage);
Storyboard.SetTargetProperty(animY, "(Canvas.Top)");

StarStoryboard.Children.Add(animX);
StarStoryboard.Children.Add(animY);

Storyboard 在 uwp 应用程序中用于使用时间轴控制动画。但是 Storyboard.

的 uwp 中没有 MediaTimeLine

I am trying to play a sound with my animation

如果你只是想在动画中播放一个声音,你可以添加一个Media​Element。并在开始 Storyboard 时按 MediaElement 播放声音,并在 Storyboard 完成时暂停声音。例如:

XAML代码

<Button
    Canvas.Top="250"
    Margin="2"
    Click="Animation_Begin"
    Content="Begin" />
<Canvas>
    <Image
        x:Name="MyImage"
        Width="50"
        Height="50"
        Source="Assets/caffe1.jpg" />
</Canvas>
<MediaElement
    x:Name="mediaforanimation"
    AutoPlay="False"
    Source="Assets.mp3" />

代码隐藏

Storyboard StarStoryboard = new Storyboard();
public Storyboardbegin()
{
    this.InitializeComponent();
    StarStoryboard.Completed += StarStoryboard_Completed;
    DoubleAnimation animX = new DoubleAnimation();
    DoubleAnimation animY = new DoubleAnimation();
    animX.Duration = TimeSpan.FromMilliseconds(600);
    animY.Duration = TimeSpan.FromMilliseconds(800);
    animX.From = 0;
    animX.To = 200;
    animY.From = 0;
    animY.To = 200;     
    Storyboard.SetTarget(animX, this.MyImage);
    Storyboard.SetTargetProperty(animX, "(Canvas.Left)");
    Storyboard.SetTarget(animY, this.MyImage);
    Storyboard.SetTargetProperty(animY, "(Canvas.Top)");
    StarStoryboard.Children.Add(animX);
    StarStoryboard.Children.Add(animY);
}

private void StarStoryboard_Completed(object sender, object e)
{
    mediaforanimation.Pause();
}

private void Animation_Begin(object sender, RoutedEventArgs e)
{ 
    StarStoryboard.Begin();
    mediaforanimation.Play();          
}     

如果这不能满足您的要求,您可以详细说明您实际想要做什么,我们可以尝试uwp中的API来做。