次の方法で共有


Playing a Video

Demonstrates how to use the VideoPlayer to play a video.

Complete Sample

The code in this topic shows you the technique for playing a video. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Download VideoPlayback_Sample.zip

Playing a Video

To play a video

Add a video to the game project using the steps outlined in loading resources.

  1. In LoadContent, load the video using the ContentManager.

  2. Create a new instance of the VideoPlayer.

    Video video;
    VideoPlayer player;
    Texture2D videoTexture;
    
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        video = Content.Load<Video>("video");
        player = new VideoPlayer();
    }
    
  3. In the Update method, play the video.

    Tip

    Set IsLooped to true if you want the video to repeat.

    protected override void Update(GameTime gameTime)
    {
        ...
        if (player.State == MediaState.Stopped)
        {
            player.IsLooped = true;
            player.Play(video);
        }
        ...
        base.Update(gameTime);
    }
    
  4. In Draw, if the VideoPlayer is not stopped, call GetTexture to get a copy of the latest frame of video.

  5. Create a Rectangle defining where on-screen the video will appear.

  6. If the texture is not null, draw it on-screen using SpriteBatch.Draw.

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
    
        // Only call GetTexture if a video is playing or paused
        if (player.State != MediaState.Stopped)
            videoTexture = player.GetTexture();
    
        // Drawing to the rectangle will stretch the 
        // video to fill the screen
        Rectangle screen = new Rectangle(GraphicsDevice.Viewport.X,
            GraphicsDevice.Viewport.Y,
            GraphicsDevice.Viewport.Width,
            GraphicsDevice.Viewport.Height);
    
        // Draw the video, if we have a texture to draw.
        if (videoTexture != null)
        {
            spriteBatch.Begin();
            spriteBatch.Draw(videoTexture, screen, Color.White);
            spriteBatch.End();
        }
    
        base.Draw(gameTime);
    }
    

See Also

Concepts

Media Overview

Reference

Video Class
VideoPlayer Class