Playing a Video on a Surface
Complete Sample
The code in this topic shows you the technique for playing a video on a quad's surface. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.
Playing Video
To play a video
-
Create a quad (or other 2D or 3D surface) on which to display the video.
-
Create a View and Projection matrix for viewing the quad.
protected override void Initialize() { // Create a scene, including a quad and a view matrix looking at it quad = new Quad(Vector3.Zero, Vector3.Backward, Vector3.Up, 1, 1); viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 2), Vector3.Zero, Vector3.Up); projectionMatrix = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, 4.0f / 3.0f, 1, 500); base.Initialize(); }
- Add a video to the game project using the steps outlined in loading resources.
- In LoadContent, use the ContentManager to load the video.
-
Create a new instance of the VideoPlayer.
Tip Set IsLooped to true if you want the video to repeat.
-
Set up your Effect for drawing.
Note In this case, we use BasicEffect, enabling default lighting and a texture.
protected override void LoadContent() { // Load a video, and initialize a player video = Content.Load<Video>("video"); player = new VideoPlayer(); player.IsLooped = true; // Setup our BasicEffect for drawing the quad worldMatrix = Matrix.CreateScale(video.Width / (float)video.Height, 1, 1); basicEffect = new BasicEffect(graphics.GraphicsDevice); basicEffect.EnableDefaultLighting(); basicEffect.World = worldMatrix; basicEffect.View = viewMatrix; basicEffect.Projection = projectionMatrix; basicEffect.TextureEnabled = true; // Create a vertex declaration vertexDeclaration = new VertexDeclaration( new VertexElement[] { new VertexElement(0, VertexElementFormat.Vector3,VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Vector3,VertexElementUsage.Normal, 0), new VertexElement(24, VertexElementFormat.Vector2,VertexElementUsage.TextureCoordinate,0) } ); }
-
In the Update method, play the video.
- In Draw, if the VideoPlayer is not stopped, call GetTexture to get a copy of the latest frame of video, and link it to your effect.
-
Draw the object using your effect.
protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // If the video is playing, get the current frame // as a texture. (Calling GetTexture on a stopped // player results in an exception) if (player.State == MediaState.Playing) basicEffect.Texture = player.GetTexture(); // Draw the quad foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) { pass.Apply(); GraphicsDevice.DrawUserIndexedPrimitives <VertexPositionNormalTexture>( PrimitiveType.TriangleList, quad.Vertices, 0, 4, quad.Indexes, 0, 2); } base.Draw(gameTime); }