A Component that ensures a background music SoundEvent is playing. OnStart stops all sounds, and OnUpdate checks a static Bgmmanager.soundHandle to start or restart the BGM when it is null, not playing, or marked Finished.
using Sandbox;
public sealed class GameMusic2 : Component
{
[Property] public SoundEvent BgmEvent { get; set; }
protected override void OnStart()
{
Sound.StopAll( 0f );
}
protected override void OnUpdate()
{
if ( Bgmmanager.soundHandle == null || !Bgmmanager.soundHandle.IsPlaying )
{
Bgmmanager.soundHandle = Sound.Play( BgmEvent );
}
// Start the sound if it isn't playing yet
if ( Bgmmanager.soundHandle.Finished )
{
Bgmmanager.soundHandle = Sound.Play( BgmEvent );
}
}
}