Saturday, June 29, 2013

I. Playing with Sounds



A game without sound effects or background music seems to be boring. Xna framework allows it users to play different sound files. There are several ways to do this, you can use a wave file, mp3 file and even make your own sound library using XACT. Xact is automatically installed into your computer upon installing XNA. To play a mp3/wma sound, you may use this method.

Create a new project and name it whatever you want..

Grab a mp3 file on your computer, any song or sound will do.

The Contents we need:

A font to show the information about the song and a sound file. To create a SpriteFont click Here.
Import it on your game content and declare a new variable for our sound file.

Song song;
SpriteFont font;

At your load content, load the content into your value.

song = Content.Load("filename of song"); //MAKE SURE THE NAME OF THE SOUND IS SAME WITH THE NAME ON THE ASSET PROPERTY
font = Content.Load("name of font");
finally, play the song..

MediaPlayer.Play(song);

On your draw method, draw the information.

            spriteBatch.Begin();
            spriteBatch.DrawString(font, song.Name, Vector2.Zero, Color.Black);
            spriteBatch.End();

Run the game and listen like a boss.

SOURCE CODE


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;

namespace sounds
{
  
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Song song;
        SpriteFont font;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

       
        protected override void Initialize()
        {
   

            base.Initialize();
        }

        protected override void LoadContent()
        {
           
            spriteBatch = new SpriteBatch(GraphicsDevice);
            song = Content.Load("2 The Reluctant Heroes");
            font = Content.Load("font");
            MediaPlayer.Play(song);
        }
        protected override void UnloadContent()
        {
         }

     
        protected override void Update(GameTime gameTime)
        {
         
            
         

            base.Update(gameTime);
        }

    
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.DrawString(font, song.Name, Vector2.Zero, Color.Black);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}