MusicPlayer

Started by xraybeesx · 3 months ago · 2 replies · 89 views

#1
xraybeesx
Member
JoinedApr 2026 Posts19 Score1,160
Does anyone have any examples on how to use the MusicPlayer?

I just want to add some background music to my game and I can't find anything info on this.  Sound effects are easy enough and there are plenty of tutorials on those, but I have no idea how to add music.
edited 3 months ago#2
xraybeesx
Member
JoinedApr 2026 Posts19 Score1,160
edited 3 months ago#3
xraybeesx
Member
JoinedApr 2026 Posts19 Score1,160

Okay I think I figured It out.  I create an Empty with this code in each scene:

 
using Sandbox;

public sealed class GameMusic : Component
{
	[Property] public SoundEvent BgmEvent { get; set; }
	protected override void OnUpdate()
	{
		if ( Bgmmanager.soundHandle == null || !Bgmmanager.soundHandle.IsPlaying )
		{

			Bgmmanager.soundHandle = Sound.Play( BgmEvent );
		}

		// Start the sound if sound has finished
		if ( Bgmmanager.soundHandle.Finished )
		{
			Bgmmanager.soundHandle = Sound.Play( BgmEvent );
		}
	}
}
 Then I create my soundhandle as a public static class that lives in my Code folder:
 
using Sandbox;

public static class Bgmmanager 
{
 [Property] public static SoundHandle soundHandle { get; set; }
}
 This keeps the soundhandle alive through each scene and re accesses the SoundEvent in whatever scene the current song ends giving me a continuous shuffle of all my music tracks. 
people
Log in to reply
You can't reply if you're not logged in. That would be crazy.