1. Post #1
    XXSkullmanXX's Avatar
    May 2008
    11 Posts
    Hey!

    I need a luafile that randomly plays backgroundmusic like in games such as Call of Duty or Assassins Creed. Unfortunately, I can't code. Could anyone help me?

    Thanks :D

  2. Post #2
    Gold Member
    thejjokerr's Avatar
    December 2007
    2,103 Posts
    Where do you want it to play? The main menu? Or in a server?

  3. Post #3
    XXSkullmanXX's Avatar
    May 2008
    11 Posts
    It should be in the server :)

  4. Post #4
    Gold Member
    thejjokerr's Avatar
    December 2007
    2,103 Posts
    It is very, very late and I have no idea if this'll work:
    if SERVER then
        AddCSLuaFile("random_music.lua");
           
        return;
    end;
    
    local randomSongs = {
        [1] = { "path/to/song.mp3", 20 },    -- Plays for 20 seconds
        [2] = { "path/to/song2.mp3", 30 }    -- Plays for 30 seconds
    };
    
    hook.Add("Think", "ShouldWePlaySong", function()
        if GetPlayingSound then
            if GetPlayingSound:IsPlaying() then
                if PlayingSoundTimeEnd < CurTime() then
                    -- The sound should stop playing, continue to the next random sound.
                    GetPlayingSound:Stop();
                    
                    GetPlayingSound = nil;
                end;
            else
                GetPlayingSound:Play();
            end;
        else
            local rndom = table.Random(randomSongs);
            
            GetPlayingSound = CreateSound(LocalPlayer(), rndom[1] );
            
            PlayingSoundTimeEnd = CurTime() + rndom[2];
        end;
    end);

  5. Post #5
    XXSkullmanXX's Avatar
    May 2008
    11 Posts
    Thank you soo much :D I'm going to try it out later :)

  6. Post #6
    XXSkullmanXX's Avatar
    May 2008
    11 Posts
    It works! :D Thank you soo much again :)

  7. Post #7
    XXSkullmanXX's Avatar
    May 2008
    11 Posts
    Do you mind, if I make an addon out of this, post it on garrysmod.org and credit you for creating the script?