Condividi tramite


Procedura: controllare un oggetto MediaElement (Play, Pause, Stop, Volume e Speed)

Aggiornamento: novembre 2007

Nell'esempio riportato di seguito viene illustrato come controllare la riproduzione dei supporti multimediali tramite MediaElement. In questo esempio viene creato un semplice lettore multimediale che consente di riprodurre, mettere in pausa, interrompere e andare avanti e indietro all'interno del contenuto del supporto multimediale, oltre a regolare volume e velocità.

Esempio

Nel codice riportato di seguito viene creata l'interfaccia utente.

Nota

La proprietà LoadedBehavior di MediaElement deve essere impostata su Manual per essere in grado di interrompere, mettere in pausa e riprodurre in modo interattivo il supporto multimediale.

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

  <StackPanel Background="Black">

    <!-- To interactively stop, pause, and play the media, the LoadedBehavior 
           property of the MediaElement must be set to "Manual". -->
    <MediaElement Source="media\numbers.wmv" Name="myMediaElement" 
     Width="450" Height="250" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill" 
     MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded"/>

    <StackPanel HorizontalAlignment="Center" Width="450" Orientation="Horizontal">

      <!-- Play button. -->
      <Image Source="images\UI_play.gif" MouseDown="OnMouseDownPlayMedia" Margin="5" />

      <!-- Pause button. -->
      <Image Source="images\UI_pause.gif" MouseDown="OnMouseDownPauseMedia" Margin="5" />

      <!-- Stop button. -->
      <Image Source="images\UI_stop.gif" MouseDown="OnMouseDownStopMedia" Margin="5" />

      <!-- Volume slider. This slider allows a Volume range between 0 and 1. -->
      <TextBlock Foreground="White" VerticalAlignment="Center" Margin="5"  >Volume</TextBlock>
      <Slider Name="volumeSlider" VerticalAlignment="Center" ValueChanged="ChangeMediaVolume" 
       Minimum="0" Maximum="1" Value="0.5" Width="70"/>

      <!-- Volume slider. This slider allows a Volume range between 0 and 10. -->
      <TextBlock Foreground="White" Margin="5"  VerticalAlignment="Center">Speed</TextBlock>
      <Slider Name="speedRatioSlider" VerticalAlignment="Center" ValueChanged="ChangeMediaSpeedRatio" 
       Value="1" Width="70" />

      <!-- Seek to slider. Ths slider allows you to jump to different parts of the media playback. -->
      <TextBlock Foreground="White" Margin="5"  VerticalAlignment="Center">Seek To</TextBlock>
      <Slider Name="timelineSlider" Margin="5" ValueChanged="SeekToMediaPosition" Width="70"/>

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

  <StackPanel Background="Black">

    <!-- To interactively stop, pause, and play the media, the LoadedBehavior 
           property of the MediaElement must be set to "Manual". -->
    <MediaElement Source="media\numbers.wmv" Name="myMediaElement" 
     Width="450" Height="250" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill" 
     MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded"/>

    <StackPanel HorizontalAlignment="Center" Width="450" Orientation="Horizontal">

      <!-- Play button. -->
      <Image Source="images\UI_play.gif" MouseDown="OnMouseDownPlayMedia" Margin="5" />

      <!-- Pause button. -->
      <Image Source="images\UI_pause.gif" MouseDown="OnMouseDownPauseMedia" Margin="5" />

      <!-- Stop button. -->
      <Image Source="images\UI_stop.gif" MouseDown="OnMouseDownStopMedia" Margin="5" />

      <!-- Volume slider. This slider allows a Volume range between 0 and 1. -->
      <TextBlock Foreground="White" VerticalAlignment="Center" Margin="5"  >Volume</TextBlock>
      <Slider Name="volumeSlider" VerticalAlignment="Center" ValueChanged="ChangeMediaVolume" 
       Minimum="0" Maximum="1" Value="0.5" Width="70"/>

      <!-- Volume slider. This slider allows a Volume range between 0 and 10. -->
      <TextBlock Foreground="White" Margin="5"  VerticalAlignment="Center">Speed</TextBlock>
      <Slider Name="speedRatioSlider" VerticalAlignment="Center" ValueChanged="ChangeMediaSpeedRatio" 
       Value="1" Width="70" />

      <!-- Seek to slider. Ths slider allows you to jump to different parts of the media playback. -->
      <TextBlock Foreground="White" Margin="5"  VerticalAlignment="Center">Seek To</TextBlock>
      <Slider Name="timelineSlider" Margin="5" ValueChanged="SeekToMediaPosition" Width="70"/>

    </StackPanel>
  </StackPanel>
</Page>

Nel codice riportato di seguito viene implementata la funzionalità dei controlli interfaccia utente. I metodi Play, Pause e Stop vengono utilizzati, rispettivamente, per riprodurre, mettere in pausa e interrompere il supporto multimediale. La modifica della proprietà Position di MediaElement consente di spostarsi nel contenuto del supporto multimediale. Infine, le proprietà Volume e SpeedRatio vengono utilizzate per regolare il volume e la velocità di riproduzione del supporto multimediale.

Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Imports System.Windows.Data
Imports System.Windows.Media
Imports System.Windows.Input

Namespace SDKSample

    Partial Class MediaElementExample
        Inherits Page

        ' Play the media.
        Sub OnMouseDownPlayMedia(ByVal sender As Object, ByVal args As MouseButtonEventArgs)

            ' The Play method will begin the media if it is not currently active or 
            ' resume media if it is paused. This has no effect if the media is
            ' already running.
            myMediaElement.Play()

            ' Initialize the MediaElement property values.
            InitializePropertyValues()

        End Sub 'OnMouseDownPlayMedia


        ' Pause the media.
        Sub OnMouseDownPauseMedia(ByVal sender As Object, ByVal args As MouseButtonEventArgs)

            ' The Pause method pauses the media if it is currently running.
            ' The Play method can be used to resume.
            myMediaElement.Pause()

        End Sub 'OnMouseDownPauseMedia


        ' Stop the media.
        Sub OnMouseDownStopMedia(ByVal sender As Object, ByVal args As MouseButtonEventArgs)

            ' The Stop method stops and resets the media to be played from
            ' the beginning.
            myMediaElement.Stop()

        End Sub 'OnMouseDownStopMedia


        ' Change the volume of the media.
        Private Sub ChangeMediaVolume(ByVal sender As Object, ByVal args As RoutedPropertyChangedEventArgs(Of Double))
            myMediaElement.Volume = System.Convert.ToDouble(volumeSlider.Value)

        End Sub 'ChangeMediaVolume

        ' Change the speed of the media.
        Private Sub ChangeMediaSpeedRatio(ByVal sender As Object, ByVal args As RoutedPropertyChangedEventArgs(Of Double))
            myMediaElement.SpeedRatio = System.Convert.ToDouble(speedRatioSlider.Value)

        End Sub 'ChangeMediaSpeedRatio

        ' 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 args As RoutedEventArgs)
            timelineSlider.Maximum = myMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds
        End Sub

        ' When the media playback is finished. Stop() the media to seek to media start.
        Private Sub Element_MediaEnded(ByVal sender As Object, ByVal args As RoutedEventArgs)
            myMediaElement.Stop()
        End Sub

        ' Jump to different parts of the media (seek to). 
        Private Sub SeekToMediaPosition(ByVal sender As Object, ByVal args As RoutedPropertyChangedEventArgs(Of Double))
            Dim SliderValue As Integer = CType(timelineSlider.Value, Integer)

            ' Overloaded constructor takes the arguments days, hours, minutes, seconds, miniseconds.
            ' Create a TimeSpan with miliseconds equal to the slider value.
            Dim ts As New TimeSpan(0, 0, 0, 0, SliderValue)
            myMediaElement.Position = ts
        End Sub

        ' Set the media's starting Volume and SpeedRatio to the current value of the
        ' their respective slider controls.
        Private Sub InitializePropertyValues()
            myMediaElement.Volume = System.Convert.ToDouble(volumeSlider.Value)
            myMediaElement.SpeedRatio = System.Convert.ToDouble(speedRatioSlider.Value)
        End Sub
    End Class 'MediaElementExample
End Namespace 'SDKSample
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Input;

namespace SDKSample
{

   public partial class MediaElementExample : Page
   {

      // Play the media.
      void OnMouseDownPlayMedia(object sender, MouseButtonEventArgs args)
      {

         // The Play method will begin the media if it is not currently active or 
         // resume media if it is paused. This has no effect if the media is
         // already running.
         myMediaElement.Play();

         // Initialize the MediaElement property values.
         InitializePropertyValues();

      }

      // Pause the media.
      void OnMouseDownPauseMedia(object sender, MouseButtonEventArgs args)
      {

         // The Pause method pauses the media if it is currently running.
         // The Play method can be used to resume.
         myMediaElement.Pause();

      }

      // Stop the media.
      void OnMouseDownStopMedia(object sender, MouseButtonEventArgs args)
      {

         // The Stop method stops and resets the media to be played from
         // the beginning.
         myMediaElement.Stop();

      }

      // Change the volume of the media.
      private void ChangeMediaVolume(object sender, RoutedPropertyChangedEventArgs<double> args)
      {
         myMediaElement.Volume = (double)volumeSlider.Value;
      }

      // Change the speed of the media.
      private void ChangeMediaSpeedRatio(object sender, RoutedPropertyChangedEventArgs<double> args)
      {
         myMediaElement.SpeedRatio = (double)speedRatioSlider.Value;
      }

      // 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;
      }

      // When the media playback is finished. Stop() the media to seek to media start.
      private void Element_MediaEnded(object sender, EventArgs e)
      {
         myMediaElement.Stop();
      }

      // Jump to different parts of the media (seek to). 
      private void SeekToMediaPosition(object sender, RoutedPropertyChangedEventArgs<double> args)
      {
         int SliderValue = (int)timelineSlider.Value;

         // Overloaded constructor takes the arguments days, hours, minutes, seconds, miniseconds.
         // Create a TimeSpan with miliseconds equal to the slider value.
         TimeSpan ts = new TimeSpan(0, 0, 0, 0, SliderValue);
         myMediaElement.Position = ts;
      }

      void InitializePropertyValues()
      {
         // Set the media's starting Volume and SpeedRatio to the current value of the
         // their respective slider controls.
         myMediaElement.Volume = (double)volumeSlider.Value;
         myMediaElement.SpeedRatio = (double)speedRatioSlider.Value;
      }

   }
}

Vedere anche

Attività

Procedura: controllare un MediaElement utilizzando uno storyboard