I ve read a lot and tried what people said about how to use sounds in monogame but confused, because some say use Sound some say SoundEffect, I try but something is missing.
If anyone really knows about this , please give a detailed information. There s no effect of a soundless game
First of all there are 2 ways of playing sounds in MonoGame, Song
and SoundEffect
. In short:
-
Song is used for playing background music, as such only 1 instance of a
Song
is possible at a time. It is found under Microsoft.Xna.Framework.Media namespace and you use the static class MediaPlayer to control it. -
SoundEffect on the other hand are used for sounds which can occur multiple times, it is found under Microsoft.Xna.Framework.Audio namespace and to play it all you have to do is call it’s respective
.Play
method. A wiser choice would be to create an instance of sound effect (as seen in the code bellow) so you can have more control over it.
Example code, just add your own content, and use keyboard buttons 1 - 4 to play/stop song and sound effect:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
namespace Music
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
KeyboardState kstate, prevkstate;
Song song;
SoundEffect soundEffect;
SoundEffectInstance soundEffectInstance;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load content
song = Content.Load<Song>("Awake");
soundEffect = Content.Load<SoundEffect>("Stargazer");
}
protected override void Update(GameTime gameTime)
{
kstate = Keyboard.GetState();
// Play a Song
if (kstate.IsKeyDown(Keys.D1) && prevkstate.IsKeyUp(Keys.D1))
MediaPlayer.Play(song);
// Stop a Song
if (kstate.IsKeyDown(Keys.D2) && prevkstate.IsKeyUp(Keys.D2))
MediaPlayer.Stop();
// Play a SoundEffect
if (kstate.IsKeyDown(Keys.D3) && prevkstate.IsKeyUp(Keys.D3))
{
soundEffectInstance = soundEffect.CreateInstance();
soundEffectInstance.Play();
}
// Stop a SoundEffect
if (kstate.IsKeyDown(Keys.D4) && prevkstate.IsKeyUp(Keys.D4))
soundEffectInstance?.Stop();
prevkstate = kstate;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);
}
}
}
3 Likes
a great description, thanks for sharing time to answer. Now i ll try them. Thank you