MusicPlayer

Started by xraybeesx 3 posts 88 views

Reply on sbox.game
  1. #1
    xraybeesx 1,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.
  2. edited Jun 2026 #2
    xraybeesx Started this 1,160
  3. edited Jun 2026 #3
    xraybeesx Started this 1,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.