This is my first post so let me know if I do anything wrong.
Can you give me feedback on my SoundModule? This is used for both the client and the server to play sounds. I also use sound groups so that clients can adjust the SFX and Music to their liking. However, I’m unsure of whether this is the best way to play sounds or not.
local SoundModule = {}
local Debris = game:GetService("Debris")
local SoundService = game:GetService("SoundService")
-- Can be any sound instance setting
type SoundProps = {
Volume: number?,
PlaybackSpeed: number?,
Looped: boolean?,
RollOffMode: Enum.RollOffMode?,
RollOffMaxDistance: number?,
RollOffMinDistance: number?
}
-- Generic play method
local function playSound(soundId: string | number, parent, soundGroup: string, props: SoundProps)
local sound = Instance.new("Sound")
-- Handle both raw numbers and full asset strings
if typeof(soundId) == "number" then
sound.SoundId = "rbxassetid://" .. soundId
else
sound.SoundId = soundId
end
-- Apply custom props
if props then
for k, v in props do
sound[k] = v
end
end
-- Find sound group
local sg = SoundService:FindFirstChild(soundGroup)
if not sg then
warn("SoundGroup:", soundGroup, "not found")
end
sound.SoundGroup = sg or SoundService.SFX
sound.PlayOnRemove = true
sound.Parent = parent or workspace
sound:Destroy()
return sound
end
-- Play a world-positioned sound
function SoundModule:PlayWorldSound(soundId: string | number, parent, soundGroup: string, props: SoundProps?)
props = props or {}
return playSound(soundId, parent, soundGroup, props)
end
-- Play a UI/ambient sound (no spatial effect)
function SoundModule:PlayUISound(soundId: string | number, soundGroup: string, props: SoundProps?, randOffset: number?)
props = props or {}
props.RollOffMaxDistance = nil -- No distance rolloff
props.EmitterSize = nil
local baseSpeed = props.PlaybackSpeed or 1
if randOffset and randOffset > 0 then
local randomOffset = math.random(-randOffset * 100, randOffset * 100) / 100
props.PlaybackSpeed = math.clamp(baseSpeed + randomOffset, 0.1, 10)
else
props.PlaybackSpeed = baseSpeed
end
return playSound(soundId, SoundService, soundGroup, props)
end
-- Play a sound instance
function SoundModule:PlaySoundInstance(instance: Sound)
if not instance then return end
if instance.PlayOnRemove then
warn("Sound instance has PlayOnRemove and may cause problems")
end
local sound = instance:Clone()
sound.PlayOnRemove = true
sound.Parent = instance.Parent
sound:Destroy()
end
return SoundModule