Jun 9, 2009

Controlling Audio playback in XAML

Just a quick post (mainly for my own reference). I had the need to do some simple audio playback in a WPF application recently and wanted to trigger the playback declaratively.

In the  past any media playback I have done through code behind of some sort. In this scenario the audio files were going to be more dynamic and all I needed to perform was a simple play operation. I didn’t have the need to support pausing, fast forward, rewind, etc. Just play the clip.

A little poking around on the tubes didn’t turn up much useful. Hence why I am posting this entry.

I found that if you use the MediaElement control you can trigger it using a MediaTimline element in a BeginStoryboard action.

First declare your MediaElement and simply give it an x:Name (don’t specify the source, LoadedBehavior, UnloadeBehavior etc..)

<MediaElement x:Name="mediaElement" />  


Then wherever you want to trigger the animation (on a button click in my case) put the following event trigger



<Button.Triggers>
<EventTrigger RoutedEvent="ButtonBase.Click">
<BeginStoryboard>
<Storyboard>
<MediaTimeline Source="Resources\AudioFiles\easy.wma" Storyboard.TargetName="mediaElement" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home