Getting advice on my sound module

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

Is it necessary to delete the sounds every time they’re played? Why not store the instances in a table and parent them / play them when needed?

You also import Debris and never use it.

I like what you did with the type checking and module formatting, looks good!

1 Like

you didnt do anything wrong

one thing that came to mind is that

a lot, or most, developers make this mistake: for some given action, they have only one sound

an example of this is if a player rolls in lets say a realistic-ish parkour game. you’d hear the cloth of the players clothes. but what if they keep rolling? wouldn’t that sound get repetitive?

i address this in my old game when the plr rolls Cinder - Roblox
its a real easy fix, just have multiple sounds per action and randomize them being played. a really nice level of detail. in the example, have a set of multiple cloth sounds

in your sound module you should implement this.
instead of having a single playSound(id) thing, you should have an object like sound.New(x), where x can be a list of sounds or just one. and when you call ::Play(properties) it would play one of the sounds from a temporary table that cloned x, remove it from the temporary table, and keep pulling and playing from that temporary table until its empty, and there it would reset the table so that its full of the sounds again

function sound:FromList(removeOnEnd, dontClone)
	local index = math.random(1, #self.remainingSounds)
	local value = self.remainingSounds[index]
	table.remove(self.remainingSounds, index)
	if (#self.remainingSounds <= 0) then
		self.remainingSounds = {table.unpack(self.initialSounds)}
	end
	return sound:Get(value[1], value[2], removeOnEnd, dontClone)
end

this is what i wrote in the game i linked

and my entire sound module (most of it is poorly written + its too simplistic):

Summary

local sound = {}
sound.__index = sound

local globalOverwrites = {} – overwrite all sound properties
local getSoundCache = {}

local SoundService = game:GetService(‘SoundService’)

local function getFromDirectory(dir)
if (not getSoundCache[dir]) then
local directory = SoundService
for _, v in ipairs(string.split(dir, ‘/’)) do
directory = directory:WaitForChild(v)
end
getSoundCache[dir] = directory
end
return getSoundCache[dir]
end

function sound.Get(_, directory, properties, removeOnEnd, dontClone)
local soundObject = type(directory) == ‘string’ and (getFromDirectory(directory)) or (directory) – string or instance
if (not dontClone) then
soundObject = soundObject:Clone()
end

removeOnEnd = removeOnEnd == nil and (false) or (removeOnEnd)
if (removeOnEnd) then
	task.spawn(function()
		soundObject.Ended:Wait()
		soundObject:Destroy()
	end)
end

if (not properties.Parent and not dontClone) then
	soundObject.Parent = SoundService
end

for k, v in (properties) do
	soundObject[k] = v
end

return soundObject

end

function sound.NewList(…)
– filled with arrays of sound data {[1]=sound, [2]=properties}
return setmetatable({initialSounds={…}, remainingSounds={…}}, sound)
end

function sound:AddList(properties, …)
for _, v in ipairs({…}) do
local data = {v, properties}
table.insert(self.initialSounds, data)
table.insert(self.remainingSounds, data)
end
end

function sound:FromList(removeOnEnd, dontClone)
local index = math.random(1, self.remainingSounds)
local value = self.remainingSounds[index]
table.remove(self.remainingSounds, index)
if (self.remainingSounds <= 0) then
self.remainingSounds = {table.unpack(self.initialSounds)}
end
return sound:Get(value[1], value[2], removeOnEnd, dontClone)
end

function sound:OverwriteProperties(sound, overwriteProperties)
for k, v in (overwriteProperties) do
sound[k] = v
end
return sound
end

sound.clothList = sound.NewList() do
local clothSoundProperties = {Volume = .5, RollOffMinDistance = 7, RollOffMaxDistance = 21}
for _, v in ipairs(getFromDirectory(‘sounds/cloth’):GetChildren()) do
sound.clothList:AddList(clothSoundProperties, ‘sounds/cloth/’..v.Name)
end
end

sound.fistSwingList = sound.NewList() do
local swingSoundProperties = {Volume = .5, RollOffMinDistance = 7, RollOffMaxDistance = 21}
for _, v in ipairs(getFromDirectory(‘sounds/combat/fists/swing’):GetChildren()) do
sound.fistSwingList:AddList(swingSoundProperties, ‘sounds/combat/fists/swing/’..v.Name)
end
end

return sound

you can use it for reference


for your module, if i had to point out some issues, itd definitely be the lack of an oop strucutre. i find oop works nicely with sound modules. this would remove the need to pass the soundId if u structure it like something like:

local mySound = sound.New({SoundService.Sound1, SoundService.Sound2}, defaultProperties?}

have all your sounds already in your game, in like soundservice or something. and when u do mySound:Play(), clone one of the sounds in the table (Sound1 or Sound2) and set properties and whatnot. no need to make a whole new sound yfm

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.