Adding video layers to your XNA code

Written by Dean Edis.

In our first article we covered how we can write a simplified Photoshop-style API for displaying multiple textures on the screen, and we have since extended the code to support parallax scrolling.

In this article we will add a short class which allows us to display Video objects as layers. In the future when we will develop our ‘layer’ code further we will be able to add post-processing filters (such as radial blur, grayscale, brightness/contrast), which could result in some great looking effects.

Here’s a screenshot showing video playing on one layer, with another layer showing information about the video:

(If you like the track then I recommend going to thebritishibm.com to view it in full, and more. It makes excellent music to code to!)

The code for this is quite straight-forward. When constructing a new VideoLayer object was pass in the Video we would like to play, and specify whether we want it to start playing immediately. We can optionally set whether we want the video to loop using the AutoRepeat property.

Here’s the new class:

public class VideoLayer : Layer, IDisposable
{
    private readonly Video m_video;
    private readonly bool m_autoPlay;
    private VideoPlayer m_player;
    private bool m_isFirstUpdate = true;

    /// <summary>
    /// Gets or sets a value indicating whether to automatically loop the video.
    /// </summary>
    public bool AutoRepeat
    {
        get { return m_player.IsLooped; }
        set { m_player.IsLooped = value; }
    }

    /// <summary>
    /// The constructor.
    /// </summary>
    /// <param name="video">The Video object to play.</param>
    /// <param name="autoPlay">Whether to start as video playing as soon as Update(...) is called.</param>
    public VideoLayer(Video video, bool autoPlay)
    {
        m_video = video;
        m_autoPlay = autoPlay;
        m_player = new VideoPlayer();
        AutoRepeat = true;
    }

    public void Play()
    {
        m_player.Stop();
        m_player.Play(m_video);
    }

    public void Stop()
    {
        m_player.Stop();
    }

    public override void Update(GameTime gameTime)
    {
        if (m_isFirstUpdate)
        {
            if (m_autoPlay)
                Play();
            m_isFirstUpdate = false;
        }

        base.Update(gameTime);
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.GraphicsDevice.Clear(Color.Black);

        if (m_player.State != MediaState.Stopped)
            spriteBatch.Draw(m_player.GetTexture(), Origin, CreateWhite(ActualOpacity));
    }

    public void Dispose()
    {
        if (m_player == null)
            return;
        m_player.Dispose();
        m_player = null;
    }
}

As always, you can download the full source (including a pre-built sample application showing its usage) from the link below.

DOWNLOAD SOURCE