Search code examples
audioluagarrys-mod

How to select random .wav/.mp3 file from folder with Garry's mod?


I've recently started Coding a program that will replace sound effects from a default directory, in the Source-Engine Game, Garry's Mod.

This is the current code:

function GM:PlayerFootstep( ply, pos, foot, sound, volume, rf ) 
     ply:EmitSound("gear1")
     return true 
 end

I want to emit multiple .wav Sound effects, without them overlapping, and being selected at random.

I have not found any Source helpful enough on the Internet to assist, so i resorted to Stack Overflow. I would appreciate assistance with the topic.


Solution

  • You'll want to look at the file.Find function for this.

    I'd recommend having a custom folder such as sound/customsteps/ where you can put all your custom sounds. I would also recommend using the .wav format for the sound files, but some others do work (.mp3 and .ogg if I recall correctly).

    In your code, simply call local snds=file.Find( "sound/customsteps/*", "GAME" ) which gives you a table, then you can simply choose a random one from the list using local snd=snds[math.random(1,#snds)] and play it as you do in your above code - ply:EmitSound(snd).

    Make sure you create the table of sounds outside of the GM:PlayerFootstep function, so that it only runs once. I would also recommend precaching all the sounds. You can do this by looping through the table and calling util.PrecacheSound(path) on them, like so:

    for k,v in pairs(snds) do
        util.PrecacheSound(v)
    end
    

    So, with all that in mind - your final code should look something like this:

    local snds=file.Find( "sound/customsteps/*", "GAME" )
    for k,v in pairs(snds) do
        util.PrecacheSound(v)
    end
    
    function GM:PlayerFootstep( ply, pos, foot, sound, volume, rf ) 
        ply:EmitSound(snds[math.random(1,#snds)])
        return true
    end
    

    Source: personal experience