Play sound as looping music & obey music volume ?

How would I play a sound file in Garrys Mod as music, on a loop, and obey the user’s music volume setting?

I think that I can use the below to play a sound at the players music volume, but it doesn’t get louder / quieter when the user changes their music volume, and doesn’t loop.


local MyMusic = Sound("path/to/my/music/file.wav")
local MyMusicVolume = ConVar:GetFloat("snd_musicvolume")
local MyMusicInstance = sound.PlaySound(MyMusic, Vector(0,0,0),SNDLVL_NONE, 100, MyMusicVolume)


I’ve had a look at https://wiki.garrysmod.com/page/Creating_Looping_Sounds but that just gets you to loop the sound file itself, not looping in game.

As for the volume change, I know I can use a hook like below to watch for the convar change, but how do I change the volume of the sound?



cvars.AddChangeCallback("snd_musicvolume", function()
-- do something when the volume gets changed
end)


Any thoughts?

For starters, sound.PlaySound doesn’t exist. You’re looking for sound.Play(). Also, you cannot use SNDLVL_NONE because those enums are not for the function you are using. Instead, use https://wiki.garrysmod.com/page/Global/CreateSound and follow the example. Then, use https://wiki.garrysmod.com/page/CSoundPatch/ChangeVolume in your “cvars.AddChangeCallback”.

As for looping sounds, use https://wiki.garrysmod.com/page/Global/SoundDuration on a timer and if you want it to stop after a certain amount of seconds, create another timer for the amount of time and remove the timer playing the sound and stop the sound.