Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-04 05:34
7.2%
Getting Started with XNA Game Studio 3.0 to develop video games (Part VII).

by Uditha Bandara


This month we`ll discuss about code and steps to use music and audio in a pc game.

First you need to add Music files (.mp3, .wav) to the content folder in a new XNA project.


 

Then you are able to write a code for using audio in a PC game.

In the Game1.cs file initialize these variables.

Song mysong;//initialize the song

       

SpriteFont myfont;//initialize font

      

 String val;

      

 Texture2D mytx;//initialize texture

 



Now in the LoadContent() method write code for loading the assest

 

  Window.AllowUserResizing = true;

 

          

 //first add new mp3 to a content folder

         

mysong = Content.Load<Song>("sum41");//load the mp3

          

myfont = Content.Load<SpriteFont>("Arial");//load the font

           

mytx = Content.Load<Texture2D>("B");//load the image

 

         

 MediaPlayer.Play(mysong);//play the song

 

 

 

Then in the Update() method you can write this code segment.

 

//simple text effect

           

if (gameTime.TotalGameTime.Seconds % 2 == 0)

           

{

             

  val = "Playing -sum 41";

          

 }

          

 else

          

 {

             

  val = "";

 

 }

 

 

 In the Draw () method you can see the Changes by drawing the images.

 

 

spriteBatch.Begin();  //begin spite batch process

 

          

 

 spriteBatch.Draw(mytx, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),

                Color.White); 

//draw image

 

           

spriteBatch.DrawString(myfont, val,

               new Vector2(30.0f, 30.0f), Color.Orange);

//draw the font

      

 

 

 spriteBatch.End();//end spite batch process

 

 

Now you can run the project by pressing F5 or by clicking the run button.

 




 

Final code of Game1.cs

 

 

/*

 content created by -uditha sampath bandara

 udithamail@yahoo.com

 uditha.wordpress.com

*/

 

 

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Content;

using Microsoft.Xna.Framework.GamerServices;

using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Media;

using Microsoft.Xna.Framework.Net;

using Microsoft.Xna.Framework.Storage;

 

namespace Using_Audio_in_XNA_game

{

    /// <summary>

    /// This is the main type for your game

    /// </summary>

    public class Game1 : Microsoft.Xna.Framework.Game

    {

        GraphicsDeviceManager graphics;

        SpriteBatch spriteBatch;

 

        Song mysong;//initialize the song

        SpriteFont myfont;//initialize font

        String val;

        Texture2D mytx;//initialize texture

 

 

        public Game1()

        {

            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";

        }

 

        /// <summary>

        /// Allows the game to perform any initialization it needs to before starting to run.

        /// This is where it can query for any required services and load any non-graphic

        /// related content.  Calling base.Initialize will enumerate through any components

        /// and initialize them as well.

        /// </summary>

        protected override void Initialize()

        {

          

 

            base.Initialize();

        }

 

        /// <summary>

        /// LoadContent will be called once per game and is the place to load

        /// all of your content.

        /// </summary>

        protected override void LoadContent()

        {

            // Create a new SpriteBatch, which can be used to draw textures.

            spriteBatch = new SpriteBatch(GraphicsDevice);

 

            Window.AllowUserResizing = true;

 

            //first add new mp3 to a content folder

            mysong = Content.Load<Song>("sum41");//load the mp3

            myfont = Content.Load<SpriteFont>("Arial");//load the font

            mytx = Content.Load<Texture2D>("B");

 

            MediaPlayer.Play(mysong);//play the song

 

         

        }

 

        /// <summary>

        /// UnloadContent will be called once per game and is the place to unload

        /// all content.

        /// </summary>

        protected override void UnloadContent()

        {

           

        }

 

        /// <summary>

        /// Allows the game to run logic such as updating the world,

        /// checking for collisions, gathering input, and playing audio.

        /// </summary>

        /// <param name="gameTime">Provides a snapshot of timing values.</param>

        protected override void Update(GameTime gameTime)

        {

            // Allows the game to exit

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

                this.Exit();

 

            //simple text effect

            if (gameTime.TotalGameTime.Seconds % 2 == 0)

            {

                val = "Playing -sum 41";

            }

            else

            {

                val = "";

 

            }

 

 

 

            base.Update(gameTime);

        }

 

        /// <summary>

        /// This is called when the game should draw itself.

        /// </summary>

        /// <param name="gameTime">Provides a snapshot of timing values.</param>

        protected override void Draw(GameTime gameTime)

        {

            GraphicsDevice.Clear(Color.Black);

 

 

            spriteBatch.Begin();  //begin spite batch prosess

 

            spriteBatch.Draw(mytx, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),

                Color.White);  //draw image

 

            spriteBatch.DrawString(myfont, val,

               new Vector2(30.0f, 30.0f), Color.Orange);//draw the font

      

 

 

            spriteBatch.End();//end spite batch process

 

 

            base.Draw(gameTime);

        }

    }

}

 

 

 

 

This is the end of the using Music/Audio in a PC game tutorial.

Also source project is attached with this article. ( http://digit.lk/downloads/Oct09/UsingAudioinXNAgame.rar )

 

Form the next tutorial you`ll learn about working with 3D coalition in a XNA game.

 

 

 

 

 

 

 



 

Previous Article