Playing a Song

Won't work for some reason

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

41 Replies - 18078 Views - Last Post: 26 June 2010 - 05:15 PM

#1 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Playing a Song

Posted 20 June 2010 - 05:00 PM

This is the error message I'm getting:
Error loading "Sounds\ShadowRainMenu". File contains Microsoft.Xna.Framework.Audio.SoundEffect but trying to load as Microsoft.Xna.Framework.Media.Song.



And this is the line that gets this error(in LoadContent()):
//Songs for different screens
            menuSong = Content.Load<Song>("Sounds\\ShadowRainMenu");



When ever my StartScreen is the active screen, this is suppose to play.

StartScreen is a different class than the one the above code is in. The above code is in Game1 class.

StartScreen:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input;

namespace fullGame1
{
    class StartScreen : GameScreen//inherits from GameScreen so has all the functionality of it and can override
    {
        MenuComponent menuComponent;
        Texture2D image;//background image
        Rectangle imageRectangle;//rectangle used for the background
        SoundEffect sound;//sound to be played

        KeyboardState keyboardState;


        

        public int SelectedIndex//property to get and set the SelectedIndex property of the MenuComponent
        {
            get { return menuComponent.SelectedIndex; }
            set { menuComponent.SelectedIndex = value; }
        }

        //constructor- Game, SpriteBatch, SpriteFont, Texture2DSz
        public StartScreen(Game game, SpriteBatch spriteBatch,
                                SpriteFont spriteFont, Texture2D image, SoundEffect sound): base(game, spriteBatch)
        {
            string[] menuItems = { "Start Game", "End Game" };

            menuComponent = new MenuComponent(game, spriteBatch, spriteFont, menuItems);//creates new menuComponent
            Components.Add(menuComponent);//add menuComponent to the list of components of the game
            //^because the component was added to the list of components of the game, its Update method
            //will automatically be called with base.Update() is called

            this.image = image;//sets image field to the image being passed in
            this.sound = sound;//sets the sound field to the sonud being passed in

            //create rectangle starting in top left and covering the whole screen
            imageRectangle = new Rectangle(0, 0, Game.window.ClientBounds.Width, Game.window.ClientBounds.Height);
        }

        


        //override so that the menu will update itself
        public override void Update(GameTime gameTime)//inherit from GamScreen
        {
            keyboardState = Keyboard.GetState();

            if(keyboardState.IsKeyDown(Keys.Up) || keyboardState.IsKeyDown(Keys.Down))
            {
                //float volume = 1.0f;
                //float pitch = -1.0f;//pictch -1 down an octave, 0 normal, 1 up an octave
                //float pan = -1.0f;//pan -1 left speaker only, 0 both speakers, 1 right speaker only
                //bool loop = true;//true it continually loops
                //sound.Play(volume, pitch, pan, loop);

                float volume = 0.5f;
                sound.Play(volume);
            }

            base.Update(gameTime);
        }

        /*private bool CheckKey(Keys theKey)
        {
            return keyboardState.IsKeyUp(theKey) &&//is the key currently up
                oldKeyboardState.IsKeyDown(theKey);//and was it down in the last frame
        }
         */

        public override void Draw(GameTime gameTime)
        {
            //draw the backgroundTexture, rendering to the screen rectangle, using it's default colors
            spriteBatch.Draw(image, imageRectangle, Color.White);
            base.Draw(gameTime);//all child components, if they are visible, are drawn.
        }
    }

    
}



Here's where I tell Game1 to play the music:
 protected override void Update(GameTime gameTime)
        {
            keyboardState = Keyboard.GetState();//get the state of the keyboard


            if (activeScreen == startScreen)//if the active screen is startScreen...
            {
                MediaPlayer.IsRepeating = true;//the song will repeat
                MediaPlayer.Play(menuSong);
                HandleStartScreen();//user input on StartScreen
            }
            else if (activeScreen == actionScreen)//if the active screen is actionScreen
            {
                HandleActionScreen();//user input on actionScreen
            }
            else if (activeScreen == quitScreen)//if the active screen is quitScreen
            {
                HandleQuitScreen();//user input on quitScreen
            }

            base.Update(gameTime);//in by defualt, just keep it

            oldKeyBoardState = keyboardState;//the oldKeyBoardState is now what you just pressed
        }



And here's that whole class:
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 fullGame1
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        

        //use these to check if the player has selected a menu item when StartScreen is active
        KeyboardState keyboardState;//current state of keyboard
        KeyboardState oldKeyBoardState;//last state of keyboard

        GameScreen activeScreen;//which screen is active -> polymorphism since it'll be of type StartScreen or ActionScreen
        StartScreen startScreen;//StartScreen
        ActionScreen actionScreen;//ActionScreen
        PopUpScreen quitScreen;//PopUpScreen

        Texture2D backgroundTexture;

        SoundEffect menuNoise;//sound when scrolling menu

        int screenHeight, screenWidth;

        Song menuSong;//song to be played at the Main Menu


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            //COMMENT EVERYTHING BELOW OUT TO HAVE NON-FULL SCREEN GAME
            this.graphics.PreferredBackBufferWidth = 1280;
            this.graphics.PreferredBackBufferHeight = 720;

            this.graphics.IsFullScreen = true;
        }

        /// <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()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }
        
       /*Create the new screens and add them
        * to the list of components of the Game
        */
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Services.AddService(typeof(ContentManager), Content);
            
            //create new instance of StartScreen
            //this-current game object, spriteBatch-the game SpriteBatch object, Content.Load-load in content,
            //
            startScreen = new StartScreen(this, spriteBatch,
                                                Content.Load<SpriteFont>("menufont"),
                                                Content.Load<Texture2D>("Images\\background"), 
                                                Content.Load<SoundEffect>("Sounds\\menuNoise"));
            Components.Add(startScreen);//add startScreen to the list of components for the game
            startScreen.Hide();//hide the screen

            //create new instance of ActionScreen
            //same params as StartScreen
            actionScreen = new ActionScreen(this, spriteBatch,
                                                Content.Load<Texture2D>("Images\\treeBackground"));
            Components.Add(actionScreen);//add actionScreen to the list of components for the game
            actionScreen.Hide();//hide the screen

            //create a new instance of PopUpScreen ->added last because it is to be drawn on top of everything else
            //same params as all others
            quitScreen = new PopUpScreen(this, spriteBatch, Content.Load<SpriteFont>("menufont"),
                                                   Content.Load<Texture2D>("Images\\quitscreen"));
            Components.Add(quitScreen);//add quitScreen to the lift of components for the game
            quitScreen.Hide();//hide the screen

            activeScreen = startScreen;//assign startScreen to activeScreen -> polymorphism
            activeScreen.Show();//show the activeScreen


            //Songs for different screens
            menuSong = Content.Load<Song>("Sounds\\ShadowRainMenu");
            
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }


        /*will use this method for checking keys
         */
        private bool CheckKey(Keys theKey)
        {
            return keyboardState.IsKeyUp(theKey) &&
            oldKeyBoardState.IsKeyDown(theKey);
        }


        /*handles switching between screens, uses helper methods that use CheckKey
         * method for handling user input
         */
        protected override void Update(GameTime gameTime)
        {
            keyboardState = Keyboard.GetState();//get the state of the keyboard


            if (activeScreen == startScreen)//if the active screen is startScreen...
            {
                MediaPlayer.IsRepeating = true;//the song will repeat
                MediaPlayer.Play(menuSong);
                HandleStartScreen();//user input on StartScreen
            }
            else if (activeScreen == actionScreen)//if the active screen is actionScreen
            {
                HandleActionScreen();//user input on actionScreen
            }
            else if (activeScreen == quitScreen)//if the active screen is quitScreen
            {
                HandleQuitScreen();//user input on quitScreen
            }

            base.Update(gameTime);//in by defualt, just keep it

            oldKeyBoardState = keyboardState;//the oldKeyBoardState is now what you just pressed
        }
        

        /*Handle user input on StartScreen */
        private void HandleStartScreen()
        {
            if (CheckKey(Keys.Enter))//if the user presses enter...
            {
                if (startScreen.SelectedIndex == 0)//if you are on the first option (New Game)...
                {
                    activeScreen.Hide();//hide the active screen
                    activeScreen = actionScreen;//switch active screen to actionScreen
                    activeScreen.Show();//show the active screen
                }
                if (startScreen.SelectedIndex == 1)//if the user chooses the 2nd option (exit game)...
                {
                    this.Exit();//exit the game
                }
            }
        }

        /*Handle user input on ActionScreen*/
        private void HandleActionScreen()
        {
            if (CheckKey(Keys.Escape))///if user presses escape key
            {
                activeScreen.Enabled = false;//tells action screen to not update itself, but can draw itself <-paused
                activeScreen = quitScreen;//quitScreen becomes the active screen
                activeScreen.Show();//show activeScreen
            }
        }

        /*Handle user input on PopUpScreen*/
        private void HandleQuitScreen()
        {
            if (CheckKey(Keys.Enter))//if the user presses the Enter key...
            {
                if (quitScreen.SelectedIndex == 0)//if the user is over the first menu option...
                {
                    actionScreen.Hide(); //Hides the actionScreen so that the startScreen is the only visible screen
                    activeScreen.Hide();//hide the active screen
                    activeScreen = startScreen;//set startScreen as the active screen
                    activeScreen.Show();//show the active screen
                }
                else if (quitScreen.SelectedIndex == 1)//if the user is over the second menu option...
                {
                    activeScreen.Hide();//hide the active screen
                    activeScreen = actionScreen;//set actionScreen as the active screen
                    activeScreen.Show();//show the active screen
                }
            }
        }

        /// <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.CornflowerBlue);

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);//start drawing 2D images
            //DrawScenery();//call method that draws background
            base.Draw(gameTime);//draw all child components(menuComponent)
            spriteBatch.End();//stop drawing 2D images
        }

       
    }
}




This is my first time ever trying to add background music to a game. Yesterday I used the post from Hellbrorth about adding sounds to add sound effects, but I can't figure out songs.

Thanks a lot!


Edit:

I should note that the music is of type .wav

This post has been edited by eZACKe: 20 June 2010 - 05:04 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Playing a Song

#2 ShadowsEdge19   User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Playing a Song

Posted 20 June 2010 - 05:55 PM

Did you properly set the song file in the media player using the XACT3 audio creation tool?

This post has been edited by ShadowsEdge19: 20 June 2010 - 06:03 PM

Was This Post Helpful? 0
  • +
  • -

#3 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Playing a Song

Posted 20 June 2010 - 06:15 PM

I suppose I didn't seeing as I have no idea what that is. Is it needed?

This tutorial(I've never had a problem with a tutorial on this page before) doesn't mention doing that at all:

http://rbwhitaker.wi...ackground-music
Was This Post Helpful? 0
  • +
  • -

#4 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Playing a Song

Posted 20 June 2010 - 06:26 PM

Well now I've converted the file to a .mp3, and the game at least loads with no errors.

Problem is, I hear no music.

This is the code that should play the music:
if (activeScreen == startScreen)//if the active screen is startScreen...
            {
                HandleStartScreen();//user input on StartScreen
                MediaPlayer.IsRepeating = true;//the song will repeat
                MediaPlayer.Play(menuSong);
               
            }





Edit:

Trying a different way because I feel like it's a lot more efficient, yet still is not working. Doing it this way the game loads just fine, but I hear no background music.

I've decided I'd do this all in my StartScreen class, so I added a LoadContent method to that and now have this:
 protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            ContentManager Content;
            Content = (ContentManager)Game.Services.GetService(typeof(ContentManager));

            menuSong = Content.Load<Song>("Sounds\\Aosi - Shadow Rain");

            MediaPlayer.Play(menuSong);


        }



This is basically exactly what the tutorial I posted in the previous post tells me to do. Just isn't playing any music.

Any ideas?

Thanks!

This post has been edited by eZACKe: 20 June 2010 - 06:50 PM

Was This Post Helpful? 0
  • +
  • -

#5 ShadowsEdge19   User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Playing a Song

Posted 21 June 2010 - 03:10 AM

I presume you added the song as you would any other content by putting it in the Content folder using Visual Studio and not by moving the file into the folder outside of the program, if that is the case then it won't recognize it as content to be used by the program.
Was This Post Helpful? 0
  • +
  • -

#6 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Playing a Song

Posted 21 June 2010 - 05:59 AM

Haha, if only it was that easy. No, it's in a folder within Content called "Sounds". Added it just like I add everything else.

So I know that's definitely not the problem.
Was This Post Helpful? 0
  • +
  • -

#7 Hellbroth   User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Re: Playing a Song

Posted 21 June 2010 - 09:44 AM

ContentManager contentManager = new ContentManager(this.Services, @"Content"); 
            songSoundEffect = contentManager.Load<SoundEffect>("song");



You need to create a new contentManager otherwise it won't work you don't load them as you
normal load the pictures.


You should read again my tutorial :)

This post has been edited by Hellbroth: 21 June 2010 - 09:45 AM

Was This Post Helpful? 0
  • +
  • -

#8 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Playing a Song

Posted 21 June 2010 - 10:29 AM

Thank you, I'm getting a compile-time error though.

Here's my new code:

protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            ContentManager contentManager = new ContentManager(this.Services, @"Content");
             menuSong = contentManager.Load<Song>("Sounds\\Aosi - Shadow Rain");

            //menuSong = Content.Load<Song>("Sounds\\Aosi - Shadow Rain");

            MediaPlayer.Play(menuSong);


        }




The error is on this line:
 ContentManager contentManager = new ContentManager(this.Services, @"Content");



And it says:

Quote

'fullGame1.StartScreen' does not contain a definition for 'Services' and no extension method 'Services' accepting a first argument of type 'fullGame1.StartScreen' could be found (are you missing a using directive of assembly reference?


I have no idea what I'm suppose to do that this point.

This post has been edited by eZACKe: 21 June 2010 - 01:18 PM

Was This Post Helpful? 0
  • +
  • -

#9 Hellbroth   User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Re: Playing a Song

Posted 21 June 2010 - 01:43 PM

Why you are using two \\ you only need one.

 menuSong = contentManager.Load<Song>("Sounds\\Aosi - Shadow Rain");


Was This Post Helpful? 0
  • +
  • -

#10 lesPaul456   User is offline

  • D.I.C Addict
  • member icon

Reputation: 175
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Playing a Song

Posted 21 June 2010 - 02:19 PM

@Hellbroth: Yes, you do need both, unless you prefix the string with "@" or use "/" instead.

@OP: You're getting an error because you are running the code inside a screen, not the game class. Use Game.Services instead.

Of course, you could just use the game's content manager directly (Game.Content)...

This post has been edited by lesPaul456: 21 June 2010 - 02:20 PM

Was This Post Helpful? 0
  • +
  • -

#11 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Playing a Song

Posted 21 June 2010 - 03:56 PM

Well lesPaul, I tried both of your suggestions:

protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            ContentManager contentManager = new ContentManager(Game.Services, @"Content");
            menuSong = contentManager.Load<Song>("Sounds\\Aosi - Shadow Rain");

            //menuSong = Content.Load<Song>("Sounds\\Aosi - Shadow Rain");

            MediaPlayer.Play(menuSong);

            
        }



AND

 protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            //ContentManager contentManager = new ContentManager(Game.Services, @"Content");
            //menuSong = contentManager.Load<Song>("Sounds\\Aosi - Shadow Rain");

            menuSong = Game.Content.Load<Song>("Sounds\\Aosi - Shadow Rain");

            MediaPlayer.Play(menuSong);

            
        }



And thankfully, none of them produce errors.

But the problem is not solved! I still hear no background music. I assure you the file path is correct, and the file does contain music. I've had it play in this game before, but only when calling it from the Update Method of StartScreen(I'm sure you can imagine why that is not good enough for me).

I don't understand it. I feel like music should be playing.

This post has been edited by eZACKe: 21 June 2010 - 03:57 PM

Was This Post Helpful? 0
  • +
  • -

#12 SixOfEleven   User is offline

  • Planeswalker
  • member icon

Reputation: 1055
  • View blog
  • Posts: 6,643
  • Joined: 18-October 08

Re: Playing a Song

Posted 21 June 2010 - 04:04 PM

It is probably because the audio isn't being updated properly in the game component. What I found I had to do is have all audio static in the Game1 class. That way you are sure that it will be updating properly. Trying to do it outside of the Game1 class, for whatever reason, doesn't allow the music to play properly. What I would recommend is have a public, static, Song field in the game class. In any class outside of the Game1 class where you want change the song, stop the current song and set it to the song you want to play. It works well. Don't have code for you, sorry.
Was This Post Helpful? 0
  • +
  • -

#13 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Playing a Song

Posted 21 June 2010 - 04:27 PM

You mean like this?

Game1, at the top:
public static Song menuSong;//song to be played at the Main Menu



Game1, in LoadContent():
menuSong = Content.Load<Song>("Sounds\\Aosi - Shadow Rain");



StartScreen, in LoadContent():
 protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            //ContentManager contentManager = new ContentManager(Game.Services, @"Content");
            //menuSong = contentManager.Load<Song>("Sounds\\Aosi - Shadow Rain");

            //menuSong = Game.Content.Load<Song>("Sounds\\Aosi - Shadow Rain");

            MediaPlayer.Play(Game1.menuSong);

            
        }



Still doesn't play though.

I know the music works. If I just play it from the LoadContent method of Game1, then it plays no problem. Problem there is it's playing throughout the whole game, not just at the Main Menu.

I don't understand >.<

This post has been edited by eZACKe: 21 June 2010 - 04:28 PM

Was This Post Helpful? 0
  • +
  • -

#14 SixOfEleven   User is offline

  • Planeswalker
  • member icon

Reputation: 1055
  • View blog
  • Posts: 6,643
  • Joined: 18-October 08

Re: Playing a Song

Posted 22 June 2010 - 06:31 AM

Not quite what I had in mind. I will try and do a demo project and post the code for you.
Was This Post Helpful? 0
  • +
  • -

#15 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Playing a Song

Posted 22 June 2010 - 07:06 AM

That would be much appreciated!

I just don't understand why adding background music is so troublesome. Adding basic sound effects is so easy!
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3