I want to play a song in my monogame project. but I don’t know how to.
Can add mp3, ogg or wma music to Content. [all convert to xnb]
Song music;
//...
// in load:
music = Cont.Load<Song>(filename);
MediaPlayer.Play(music);
MediaPlayer.IsRepeating = true;
//...
// in update:
// ensure playing:
if (MediaPlayer.State == MediaState.Stopped) MediaPlayer.Play(music);
else if (MediaPlayer.State == MediaState.Paused) MediaPlayer.Resume();
// could have support stuff like this too:
void stop_song(bool rewind = true) {
if (rewind) MediaPlayer.Stop();
else MediaPlayer.Pause();
}
void song_unpause() { MediaPlayer.Resume(); }
void PlayMusic(Song song, bool loop)
{
MediaPlayer.Play(song);
MediaPlayer.IsRepeating = loop;
}
// stop all sound and music:
void StopAllSounds(bool allow_music, bool total_stop = false) {
if (allow_music) {
if (total_stop) MediaPlayer.Stop();
else if (MediaPlayer.State == MediaState.Playing) MediaPlayer.Pause();
}
// SoundEffectInstances - turn them all off (use array if lots)
Silence(total_stop, DragonHorseSound);
Silence(total_stop,WaterfallSound);
// etc...
}
void Silence(bool total_stop, SoundEffectInstance sfx) {
if (sfx == null) return;
if (total_stop) sfx.Stop();
else if (sfx.State == SoundState.Playing) sfx.Pause();
}
void ResumeAllSounds(bool allow_music) {
if (allow_music) { if (MediaPlayer.State == MediaState.Paused) MediaPlayer.Resume(); }
Rezume(DragonHorseSound);
Rezume(WaterfallSound);
// etc... (use array if lots..)
}
void Rezume(SoundEffectInstance sfx) {
if (sfx == null) return;
if (sfx.State == SoundState.Paused) sfx.Resume();
}
// SET MUSIC VOLUME
void SetMusicVolume(float vol)
{
MediaPlayer.Volume = vol;
// or use: MediaPlayer.Volume = vol * g.master_volume_factor;
}
1 Like
Built-in audio system is garbage. I recommend using FMOD or WWise. For FMOD, tho, I already wrote a Monogame wrapper.
1 Like