Compartilhar via


Multimedia Overview

Os recursos de multimídia em Windows Presentation Foundation (WPF) permitem que você integrar o áudio e vídeo em seus aplicativos para aprimorar a experiência do usuário. Este tópico apresenta os recursos de multimídia do WPF.

Este tópico contém as seguintes seções.

  • Media API
  • Media Playback Modes
  • MediaElement Class
  • MediaPlayer Class
  • Tópicos relacionados

Media API

O MediaElement e MediaPlayer classes são usadas para apresentar o conteúdo de áudio ou vídeo. Essas classes podem ser controladas interativamente ou por um relógio. Essas classes podem usar o Microsoft Windows Media Player 10 de controle para reprodução de mídia. Classe que você usa, depende do cenário.

MediaElementé um UIElement que é suportado pelo Sistema de layout e podem ser consumidos como o conteúdo de vários controles. Também é útil na Extensible Application Markup Language (XAML) , bem como código. MediaPlayer, por outro lado, foi projetado para Drawing objetos e carece layout suporte. Mídia carregada usando um MediaPlayer somente podem ser apresentados usando um VideoDrawing ou interagindo diretamente com um DrawingContext. MediaPlayernão pode ser usado em XAML.

Para obter mais informações sobre objetos de desenho e o contexto de desenho, consulte Visão Geral de Objetos de Desenho.

Observação

When distributing media with your application, you cannot use a media file as a project resource.In your project file, you must instead set the media type to Content and set CopyToOutputDirectory to PreserveNewest or Always.

Media Playback Modes

Observação

Both MediaElement and MediaPlayer have similar members.The links in this section refer to the MediaElement class members.Unless specifically noted, members linked to in the MediaElement class can also be found in the MediaPlayer class.

To understand media playback in Windows Presentation Foundation (WPF), an understanding of the different modes in which media can be played is required. Ambos MediaElement e MediaPlayer podem ser usados em dois modos diferentes de mídia, modo independente e o modo de relógio. The media mode is determined by the Clock property. Quando Clock é null, o objeto de mídia está em modo independente. Quando o Clock é nula, o objeto de mídia está no modo de relógio. By default, media objects are in independent mode.

Independent Mode

In independent mode, the media content drives media playback. Independent mode enables the following options:

  • Media's Uri can be directly specified.

  • Media playback can be directly controlled.

  • Media's Position and SpeedRatio properties can be modified.

Media is loaded by either setting the MediaElement object's Source property or by calling the MediaPlayer object's Open method.

To control media playback in independent mode, the media object's control methods can be used. The control methods available are Play, Pause, Close, and Stop. For MediaElement, interactive control using these methods is only available when the LoadedBehavior is set to Manual. These methods are unavailable when the media object is in clock mode.

See Como: Control a MediaElement (Play, Pause, Stop, Volume, and Speed) for an example of independent mode.

Clock Mode

In clock mode, a MediaTimeline drives media playback. Clock mode has the following characteristics:

  • Media's Uri is indirectly set through a MediaTimeline.

  • Reprodução de mídia pode ser controlada pelo relógio. The media object's control methods cannot be used.

  • Media is loaded by setting a MediaTimeline object's Source property, creating the clock from the timeline, and assigning the clock to the media object. Media is also loaded this way when a MediaTimeline inside a Storyboard targets a MediaElement.

To control media playback in clock mode, the ClockController control methods must be used. A ClockController is obtained from the ClockController property of the MediaClock. If you attempt to use the control methods of either a MediaElement or MediaPlayer object while in clock mode, an InvalidOperationException will be thrown.

See the Revisão de Animação for more information about clocks and timelines.

See Como: Control a MediaElement by Using a Storyboard for an example of clock mode.

MediaElement Class

Adding media to an application is as simple as adding a MediaElement control to the user interface (UI) of the application and providing a Uri to the media you wish to include. Todos os tipos de mídia suportados pelo Microsoft Windows Media Player 10 são suportadas no Windows Presentation Foundation (WPF). O exemplo a seguir mostra um simple uso da MediaElement na Extensible Application Markup Language (XAML).

<!-- This page shows a simple usage of MediaElement -->
<Page x:Class="MediaElementExample.SimpleUsage"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="SimpleUsage"
    >
  <StackPanel Margin="20">
    <MediaElement Source="media/numbers-aud.wmv" />
  </StackPanel>
</Page>

In this sample, media is played automatically as soon as it is loaded. Once the media has finished playing, the media is closed and all media resources are release (including video memory). This is the default behavior of the MediaElement object and is controlled by the LoadedBehavior and UnloadedBehavior properties.

Controlling a MediaElement

The LoadedBehavior and UnloadedBehavior properties control the behavior of the MediaElement when IsLoaded is true or false, respectively. The MediaState the properties are set to affect the media playback behavior. For example, the default LoadedBehavior is Play and the default UnloadedBehavior is Close. This means that as soon as the MediaElement is loaded and the preroll is complete, the media begins to play. Once playback is complete, media is closed and all media resources are released.

The LoadedBehavior and UnloadedBehavior properties are not the only way to control media playback. No modo de relógio, o relógio pode controlar a MediaElement e os métodos de controle interativo tiver o controle quando o LoadedBehavior é Manual. MediaElementmanipula nessa competição para controle avaliando as prioridades a seguintes.

  1. UnloadedBehavior. No lugar quando a mídia é descarregada. This ensures that all media resources are released by default, even when a MediaClock is associated with the MediaElement.

  2. MediaClock. No lugar quando a mídia tem um Clock. If media is unloaded, the MediaClock will take effect as long as the UnloadedBehavior is Manual. Clock mode always overrides the loaded behavior of the MediaElement.

  3. LoadedBehavior. No lugar quando a mídia é carregada.

  4. Interactive control methods. In place when LoadedBehavior is Manual. The control methods available are Play, Pause, Close, and Stop.

Displaying a MediaElement

To display a MediaElement it must have content to render and it will have its ActualWidth and ActualHeight properties set to zero until content is loaded. For audio only content, these properties are always zero. For video content, once the MediaOpened event has been raised the ActualWidth and ActualHeight will report the size of the loaded media. This means that until media is loaded, the MediaElement will not take up any physical space in the user interface (UI) unless the Width or Height properties are set.

Setting both the Width and Height properties will cause the media to stretch to fill the area provided for the MediaElement. To preserve the media's original aspect ratio, either the Width or Height property should be set but not both. Setting both the Width and Height properties will cause the media to present in a fixed element size that may not be desirable.

Para evitar a necessidade de um elemento de tamanho fixo que, Windows Presentation Foundation (WPF) pode Pré-avanço de a mídia. This is done by setting the LoadedBehavior to either Play or Pause. Em um Pause de estado, a mídia será pré-rolar e apresentará o primeiro quadro. In a Play state, the media will preroll and begin to play.

MediaPlayer Class

Where as the MediaElement class is a framework element, the MediaPlayer class is designed to be used in Drawing objects. Os objetos de desenho são usados quando você pode sacrificar os recursos de nível de estrutura para obter os benefícios de desempenho ou quando você precisar Freezable recursos. MediaPlayerpermite que você aproveite esses recursos, fornecendo o conteúdo de mídia em seus aplicativos. Like MediaElement, MediaPlayer can be used in independent or clock mode but does not have the MediaElement object's unloaded and loaded states. This reduces the playback control complexity of the MediaPlayer.

Controlling MediaPlayer

Because MediaPlayer is stateless, there are only two ways to control media playback.

  1. Interactive control methods. In place when in independent mode (null Clock property).

  2. MediaClock. No lugar quando a mídia tem um Clock.

Displaying a MediaPlayer

Technically, a MediaPlayer cannot be displayed since it has no physical representation. However, it can be used to present media in a Drawing using the VideoDrawing class. The following example demonstrates the use of a VideoDrawing to display media.

//
// Create a VideoDrawing.
//      
MediaPlayer player = new MediaPlayer();

player.Open(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative));

VideoDrawing aVideoDrawing = new VideoDrawing();

aVideoDrawing.Rect = new Rect(0, 0, 100, 100);

aVideoDrawing.Player = player;

// Play the video once.
player.Play();        

See the Visão Geral de Objetos de Desenho for more information about Drawing objects.

Consulte também

Referência

DrawingGroup

Conceitos

Sistema de layout

Outros recursos

Audio and Video How-to Topics