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

时间:2017-05-12 08:04:48

标签: c# uwp storyboard windows-10-universal

我想用动画播放声音。我已经使用StoryBoard和DoubleAnimation制作了动画。有谁知道如何添加声音?

Microsoft文档建议使用MediaTimeline类:

  

有两种方法可以使用a将时间轴与MediaElement相关联   MediaTimeline:

     
      
  1. 在故事板内部,当MediaTimeline是目标时[原文如此]   一个MediaElement,将创建一个MediaClock并将其分配给   MediaElement的关联播放器。请参见如何:控制MediaElement   通过使用故事板作为示例;

  2.   
  3. 明确创建   来自MediaTimeline的MediaClock并将其分配给MediaElement。

  4.   

Stack Overflow答案还建议使用MediaTimeline。

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

我的动画代码如下所示:

        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);

1 个答案:

答案 0 :(得分:1)

uwp app中的

Storyboard用于控制带时间轴的动画。但是MediaTimeLine的uwp中没有Storyboard

  

我正试图用我的动画播放声音

如果您只想播放动画的声音,可以添加Media​Element。当您开始MediaElement时,按Storyboard播放声音,并在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\2.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来做。