Cómo: Controlar un control MediaElement mediante un guión gráfico

Actualización: noviembre 2007

En este ejemplo se muestra cómo controlar un control MediaElement mediante una escala de tiempo MediaTimeline en un Storyboard.

Ejemplo

Al usar un objeto MediaTimeline en un Storyboard para controlar la temporización de un control MediaElement, la funcionalidad es idéntica a la de otros objetos Timeline, como las animaciones. Por ejemplo, un objeto MediaTimeline usa propiedades de Timeline, como la propiedad BeginTime, para especificar cuándo iniciar un MediaElement (iniciar la reproducción multimedia). También usa la propiedad Duration para especificar durante cuánto tiempo MediaElement está activo (duración de reproducción multimedia). Para obtener más información acerca del uso de objetos Timeline con un Storyboard, consulte Información general sobre objetos Storyboard.

En este ejemplo se muestra cómo crear un reproductor multimedia simple que usa MediaTimeline para controlar la reproducción. El reproductor multimedia incluye botones de reproducción, pausa, reanudación y detención. El reproductor también tiene un control Slider que actúa como una barra de progreso.

En el ejemplo siguiente se crea la interfaz de usuario (UI) para el reproductor multimedia.

<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" 
  x:Class="SDKSample.MediaTimelineExample" >

  <StackPanel Background="Black">

    <MediaElement Name="myMediaElement" MediaOpened="Element_MediaOpened"
     Width="260" Height="150" Stretch="Fill" />

    <!-- Button controls for play, pause, resume, and stop. -->
  <StackPanel HorizontalAlignment="Center" Width="260" Orientation="Horizontal">
    <Image Name="PlayButton" Source="images\UI_play.gif" Margin="30,10,10,10" />
    <Image Name="PauseButton" Source="images\UI_pause.gif" Margin="10" />
    <Image Name="ResumeButton" Source="images\UI_resume.gif" Margin="10" />
    <Image Name="StopButton" Source="images\UI_stop.gif" Margin="10" />
  </StackPanel>

  <!-- Ths slider shows the progress of the media. -->
  <Slider Name="timelineSlider" Margin="5" Width="250" HorizontalAlignment="Center"/>

  <StackPanel.Triggers>
    <EventTrigger RoutedEvent="Image.MouseDown" SourceName="PlayButton">
      <EventTrigger.Actions>
        <BeginStoryboard Name= "myBegin">

          <Storyboard SlipBehavior="Slip">

            <!-- The MediaTimeline controls the timing of the video and acts like other Timeline objects.  
                 For example, although the video clip (numbers.wmv) lasts longer, playback ends after six  
                 seconds because that is the duration of the MediaTimeline (Duration="0:0:6"). -->
            <MediaTimeline Source="media\numbers.wmv" Storyboard.TargetName="myMediaElement"  
             BeginTime="0:0:0" Duration="0:0:6" CurrentTimeInvalidated="MediaTimeChanged" />

          </Storyboard>
        </BeginStoryboard>
      </EventTrigger.Actions>
    </EventTrigger>

    <!-- These triggers impliment the functionality of the Pause, Resume
         and Stop buttons.-->
    <EventTrigger RoutedEvent="Image.MouseDown" SourceName="PauseButton">
      <EventTrigger.Actions>
        <PauseStoryboard BeginStoryboardName="myBegin" />
      </EventTrigger.Actions>
    </EventTrigger>
    <EventTrigger RoutedEvent="Image.MouseDown" SourceName="ResumeButton">
      <EventTrigger.Actions>
        <ResumeStoryboard BeginStoryboardName="myBegin" />
      </EventTrigger.Actions>
    </EventTrigger>
    <EventTrigger RoutedEvent="Image.MouseDown" SourceName="StopButton">
      <EventTrigger.Actions>
        <StopStoryboard BeginStoryboardName="myBegin" />
      </EventTrigger.Actions>
    </EventTrigger>
  </StackPanel.Triggers>

</StackPanel>
</Page>
<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" 
  x:Class="SDKSample.MediaTimelineExample" >

  <StackPanel Background="Black">

    <MediaElement Name="myMediaElement" MediaOpened="Element_MediaOpened"
     Width="260" Height="150" Stretch="Fill" />

    <!-- Button controls for play, pause, resume, and stop. -->
  <StackPanel HorizontalAlignment="Center" Width="260" Orientation="Horizontal">
    <Image Name="PlayButton" Source="images\UI_play.gif" Margin="30,10,10,10" />
    <Image Name="PauseButton" Source="images\UI_pause.gif" Margin="10" />
    <Image Name="ResumeButton" Source="images\UI_resume.gif" Margin="10" />
    <Image Name="StopButton" Source="images\UI_stop.gif" Margin="10" />
  </StackPanel>

  <!-- Ths slider shows the progress of the media. -->
  <Slider Name="timelineSlider" Margin="5" Width="250" HorizontalAlignment="Center"/>

  <StackPanel.Triggers>
    <EventTrigger RoutedEvent="Image.MouseDown" SourceName="PlayButton">
      <EventTrigger.Actions>
        <BeginStoryboard Name= "myBegin">

          <Storyboard SlipBehavior="Slip">

            <!-- The MediaTimeline controls the timing of the video and acts like other Timeline objects.  
                 For example, although the video clip (numbers.wmv) lasts longer, playback ends after six  
                 seconds because that is the duration of the MediaTimeline (Duration="0:0:6"). -->
            <MediaTimeline Source="media\numbers.wmv" Storyboard.TargetName="myMediaElement"  
             BeginTime="0:0:0" Duration="0:0:6" CurrentTimeInvalidated="MediaTimeChanged" />

          </Storyboard>
        </BeginStoryboard>
      </EventTrigger.Actions>
    </EventTrigger>

    <!-- These triggers impliment the functionality of the Pause, Resume
         and Stop buttons.-->
    <EventTrigger RoutedEvent="Image.MouseDown" SourceName="PauseButton">
      <EventTrigger.Actions>
        <PauseStoryboard BeginStoryboardName="myBegin" />
      </EventTrigger.Actions>
    </EventTrigger>
    <EventTrigger RoutedEvent="Image.MouseDown" SourceName="ResumeButton">
      <EventTrigger.Actions>
        <ResumeStoryboard BeginStoryboardName="myBegin" />
      </EventTrigger.Actions>
    </EventTrigger>
    <EventTrigger RoutedEvent="Image.MouseDown" SourceName="StopButton">
      <EventTrigger.Actions>
        <StopStoryboard BeginStoryboardName="myBegin" />
      </EventTrigger.Actions>
    </EventTrigger>
  </StackPanel.Triggers>

</StackPanel>
</Page>

En el ejemplo siguiente se crea la funcionalidad de la barra de progreso.

Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media


Namespace SDKSample

    Partial Class MediaTimelineExample
        Inherits Page
        ' When the media opens, initialize the "Seek To" slider maximum value
        ' to the total number of miliseconds in the length of the media clip.
        Private Sub Element_MediaOpened(ByVal sender As Object, ByVal e As RoutedEventArgs)
            timelineSlider.Maximum = myMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds

        End Sub 'Element_MediaOpened


        Private Sub MediaTimeChanged(ByVal sender As Object, ByVal e As EventArgs)
            timelineSlider.Value = myMediaElement.Position.TotalMilliseconds

        End Sub 'MediaTimeChanged
    End Class 'MediaTimelineExample
End Namespace 'SDKSample
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace SDKSample
{

    public partial class MediaTimelineExample : Page
    {
        // When the media opens, initialize the "Seek To" slider maximum value
        // to the total number of miliseconds in the length of the media clip.
        private void Element_MediaOpened(object sender, EventArgs e)
        {
            timelineSlider.Maximum = myMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
        }

        private void MediaTimeChanged(object sender, EventArgs e)
        {
            timelineSlider.Value = myMediaElement.Position.TotalMilliseconds;
        }

    }
}

Para obtener el ejemplo completo, vea Ejemplo Media Gallery.

Vea también

Tareas

Cómo: Controlar un MediaElement (Reproducir, Pausar, Detener, Volumen y Velocidad)

Ejemplo Media Gallery

Conceptos

Información general sobre objetos Storyboard

Información general sobre animaciones de fotogramas clave

Información general sobre animaciones

Información general sobre características de gráficos, animación y multimedia en WPF

Referencia

MediaElement

MediaTimeline

Storyboard

Otros recursos

Temas "Cómo..." de audio y vídeo