Topic: Playing random sounds

Hello guys i found this nice engine and decide to play with it, the first thing i did was modify the FPS Sponza demo character controller to be able to run and jump, i'm a total noob on LUA and coding but coping code from other places and even seeing how other people is using LUA i was able to do almost what i wanted, but i'm now at a roadblock with sound.

what i want is to simulate player walk sounds, so i used a Array to do that, but the sounds are playing very fast and on top of each other, how can why solve this?

This is my array code

walkSound = {} -- array
walkSound[1] = getObject("walk1")
walkSound[2] = getObject("walk2")
walkSound[3] = getObject("walk3")

function onSceneUpdate()

-- move
    if isKeyPressed("W") then
        addCentralForce(Player, {0, walkSpeed, 0}, "local")
        playsteepsounds()
    end

function playsteepsounds()
        characterSounds = math.random(#walkSound)
        playSound(walkSound[characterSounds])
    end

Re: Playing random sounds

What is the console saying when you play the game?

I don't know lua that well, but doesn't the function have to be made before you call it?

Or you could create the playsteepsounds() function outside of the onSceneUpdate() function.

I do have a question though. What is that:

(#walkSound)

part?

Last edited by Tutorial Doctor (2013-08-22 20:58:11)

Re: Playing random sounds

Hey thanks for the reply, i'm not really a coder so i don´t know what (#walkSound) does i just know that if i remove the # from it the sounds stop playing. About making the function before calling it, i did that, i forgot to put a "end" on the code above but on the real code it is there, so the playsteepsounds() function is outside the onSceneUpdate() function.

below is the full code

-----------------------------------------------------------------------------------
-- Maratis
-- Jules script test
-----------------------------------------------------------------------------------

-- get objects
Player = getObject("Player")
Head = getObject("Head")

dx = 0.0
dy = 0.0

-- walk var
walkSound = {} -- array
walkSound[1] = getObject("walk1")
walkSound[2] = getObject("walk2")
walkSound[3] = getObject("walk3")
soundLenght = 0.3

walkSpeed = 3.0


-- jump code
playMass = getMass(Player)
jumpSpeed = playMass * 50.0

Sound0 = getObject("JumpSound")
soundplay = 0


-- Run vars
runSpeed = 4.0


centerCursor()
mx = getAxis("MOUSE_X")
my = getAxis("MOUSE_Y")

-- scene update
function onSceneUpdate()

    setGravity({0,0,-2})

    coll = getNumCollisions(Player) -- for the jump code

    -- rotate Player (X mouse)
    rotate(Player, {0, 0, -1}, dx*100)
    
    -- rotate Head (Y mouse)
    rotate(Head, {-1, 0, 0}, dy*100, "local")    
    rotation = getRotation(Head)
    if rotation[1] > 90 then
        rotation[1] = 90
    elseif rotation[1] < -90 then
        rotation[1] = -90
    end

    setRotation(Head, rotation)
    
    -- move
    if isKeyPressed("W") then
        addCentralForce(Player, {0, walkSpeed, 0}, "local")
        playsteepsounds()
    end
    
    if isKeyPressed("S") then
        addCentralForce(Player, {0, -walkSpeed, 0}, "local")
    end
    
    if isKeyPressed("A") then
        addCentralForce(Player, {-3, 0, 0}, "local")
    end

    if isKeyPressed("D") then
        addCentralForce(Player, {3, 0, 0}, "local")
    end    
    
    -- run
    if isKeyPressed("W") and isKeyPressed("LSHIFT") then
        addCentralForce(Player, {0, runSpeed, 0}, "local")
    end
    
    -- jump
    if isKeyPressed("SPACE") then
        if (coll >= 1) then
            playmysound()
            addCentralForce(Player, {0, 0, jumpSpeed}, "local")
            print ("I jumped!!")
            else
                stopmysound()
            end
    end
    
    -- get mouse direction
    dx = getAxis("MOUSE_X") - mx
    dy = getAxis("MOUSE_Y") - my

    -- center cursor
    centerCursor()
    
    mx = getAxis("MOUSE_X")
    my = getAxis("MOUSE_Y")    
    
end

function playmysound()
       if soundplay == 0 then playSound(Sound0) end
       soundplay = 1
   end
   
function stopmysound()
       soundplay = 0
   end
   
 function playsteepsounds()
        characterSounds = math.random(#walkSound)
        playSound(walkSound[characterSounds])
    end

Also i got the array code idea from here http://forums.coronalabs.com/topic/3558 … ncomplete/

Last edited by Argoon (2013-08-22 21:35:41)

Re: Playing random sounds

Hi Argon. I think it is a lot simpler than this. What you want is an IF statement.

something like:

sound0 = getObject("sound0")

if isKeyPressed("W") then
         playSound(sound0)
end

Of course this would keep playing the sound after you pressed it, so you could add an ELSE IF statement or just stop the sound when the key is not pressed:

if isKeyPressed("W") then
       playSound(sound0)

elseif not isKeyPressed("W") then
      stopSound(sound0)
end

I need to check if this syntax is working. I will try this out myself and then report back.

EDIT:
The code below plays a sound as long as a key is pressed, otherwise it doesn't:

sound0 = getObject("sound0")

function onSceneUpdate()
    if isKeyPressed("W") then
        playSound(sound0)
    elseif not isKeyPressed("W") then
        stopSound(sound0)
    end

end

Last edited by Tutorial Doctor (2013-08-22 23:50:06)

Re: Playing random sounds

thanks man for taking the time to help me i really appreciate  it,  but unfortunately that code is not what i really want, on the full code i posted above you can see i already use something similar for the jump sound, now what i want is playing random foot steep sounds has the player walks, and i want a particular sound (audio length)  to wait for the other to stop playing before starting, i did something similar on Unity3D using arrays and someaudio.length plus waitForSeconds(someaudio) and it works very well. The problem i don't know how to convert the unity script code (not made by me btw) to a LUA counterpart or if maratis even has a audio length option.

Here is the Unity code just for example

var walkSounds : AudioClip[];
var audioStepLength = 0.3;


function Awake () {
    
    PlayStepSounds();
}

function PlayStepSounds () {
    var controller : CharacterController = GetComponent(CharacterController);

    while (true) {
        if (controller.isGrounded && controller.velocity.magnitude > 0.3) {
            audio.clip = walkSounds[Random.Range(0, walkSounds.length)];
            audio.Play();
            yield WaitForSeconds(audioStepLength);
        } else {
            yield;
        }
    }
}

Last edited by Argoon (2013-08-23 00:49:59)

Re: Playing random sounds

Oh! haha. I was wondering if you really wanted to play a random sound or not. hehe. Okay, I will try again.

This is fun by the way. I am sorta new to it all, but I think I can figure it out.

I am trying to get a character selection menu to work at the moment. I will try this again. BTW. Welcome!

Re: Playing random sounds

Okay, I changed quite a few things to make it a bit easier. I have the sound randomizing with the press of a button, but It only randomly chooses one when game begins. If I restart the game, then it will choose a random sound again. So I will post the progress so far:


walkSound = {} -- array
walkSound[1] = getObject("walk1")
walkSound[2] = getObject("walk2")
walkSound[3] = getObject("walk3")


--This function moves the character and plays the random sound
function Walk()
    if isKeyPressed("W") then
        addCentralForce(player, {0, walkSpeed, 0}, "local")
        PlayStepSounds()
    end
end

--This is the random sound
randomSound = walkSound[math.random(1,3)]

--This function plays the random sound
function PlayStepSounds()
        playSound(randomSound)

end

function onSceneUpdate()
        randomSound = walkSound[math.random(1,3)]
    --Walk
    Walk()
   
end

EDIT: Thanks COM3D, got it to work!

added it under the onSceneUpdate() function

Last edited by Tutorial Doctor (2013-08-23 07:48:09)

Re: Playing random sounds

argoon wrote:

i don´t know what (#walkSound) does

#walkSound returns the length of the walkSound list, approximately the number of sounds in this list.
math.random(#walkSound) generates random integer numbers between 1 and #walkSound, so your code translation is correct.

Did you check the Maratis wiki ?

@TD: your randomSound is not called by the onSceneUpdate function, so it is set once and is never updated.

Last edited by com3D (2013-08-23 06:18:14)

Re: Playing random sounds

Thanks Tutorial Doctor!! You are awesome. 

And thanks to you to com3D, for explaining that bit of code and helping TD, and yes i checked the Wiki before posting but didn't saw anything there that could help me, as i said i'm not really a coder, i'm a 3D modeler and i just like to dabble a little with code, but nothing very complex because as you saw i get stuck very easily, but i don't really have the habit of asking people for help, i try to find the answer myself by looking on the net. 

edit: Hum i used the code above and the sounds still play all very fast and on top of eachother, Tutorial Doctor are you sure it works well on your end?
Maybe some kind of timer will be needed to control the sounds timing just like on the Unity3D code.

Last edited by Argoon (2013-08-23 15:38:14)

Re: Playing random sounds

Has i said i'm not a coder so i can't really resolve this problem but from the the little i know maybe this page on the wiki will help coroutines?

Re: Playing random sounds

Hi Argoon. Yeah, the sound plays fast on my end too60, and they overlap. Whenever you put something in the onSceneUpdate() function I believe it runs every frame the game runs. I think the Maratis games run at 60 frames per second.

I will eventually tidy up the code a bit. And I do think you could use a timer, or you could use some conditional statements, or maybe a loop? I don't know.

But Argoon, you'd be surprised at just how new I am to programming. I made on here linking to a tutorial I made for beginners, teaching how to understand computer programming.

In no time, you will have the fundamentals down well enough to dig a little deeper into LUA.

(BTW, I haven't even used lua before I came to this site only a few days ago. But Lua is the easiest Language I have used yet)

Take Care!

Re: Playing random sounds

Thanks man for all your time, your work was not wasted, right now i comprehend more than what i did when trying this for the first time. smile

The answer will come one day, i will continue trying with this because i also liked LUA it indeed seams to be a much easier programing language then C# that i was trying to learn.

Re: Playing random sounds

Argoon wrote:

Thanks man for all your time, your work was not wasted, right now i comprehend more than what i did when trying this for the first time. smile

The answer will come one day, i will continue trying with this because i also liked LUA it indeed seams to be a much easier programing language then C# that i was trying to learn.

No Prob. If I can help with anything else, let me know. Take care.

Re: Playing random sounds

Try this:

walkSound = {getObject("walk1"), getObject("walk2"), getObject("walk3")}
duration = {10, 9, 11}

isPlaying = false
walkSpeed = 10


function onSceneUpdate()

    if isKeyPressed("W") then

        addCentralForce(player, {0, walkSpeed, 0}, "local")

        if not isPlaying then
            timer = 0 -- reset timer
            randomSoundID = math.random(#walkSound) -- select a random sound
            playSound(walkSound[randomSoundID]) -- start playing the sound
            isPlaying = true -- update status
        else  -- check for termination of the current sound
            timer = timer + 1
            if timer == duration[randomSoundID] then isPlaying = false end -- trigger new sound when current ends
        end

    else isPlaying = false end

end

NB: adjust durations to match your sounds' lengths

Last edited by com3D (2013-08-24 09:06:53)

Re: Playing random sounds

Thanks! com3D it works!. big_smile Now i just need to found out why it only works when used only on one direction tongue, when i use the same code on the other directions they all play fast again even the walk forward, maybe i need to separate them on individual functions (for example walk forward function a walk backward function, etc) instead of being all inside one function and separated by if statements?

edit: Separated the movements on different functions didn't worked. sad

At lest i was able to change the character Run function to be able to change the walk sound timing, now when i press shift and the character runs the sounds play faster like he is really running. big_smile

I DID IT! Sorry for the caps but i'm happy. big_smile

It was just a matter of using "elseif" for the rest of the directions and only put the "else isPlaying = false end" at the end of the "elseif" statements worked like a charm. big_smile

Thanks guys for all the help.

Last edited by Argoon (2013-08-24 16:19:44)

Re: Playing random sounds

Guys need help on one thing i made this code for my run function it works,  but really randomly the sounds stop playing even when i have the shift key down, i need to let go of the walk key (W) and press it again for them to play, what could be making this behaviour?

here is the code

duration = {30,30,30}
walkSpeed = 4

function charMovement()

    -- Walk
    if isKeyPressed("W")  and (coll > 1) then
        addCentralForce(Player, {0, walkSpeed, 0}, "local")
        playSteepSounds()
    elseif isKeyPressed("S")  and (coll > 1)  then
        addCentralForce(Player, {0, -walkSpeed, 0}, "local")
        playSteepSounds()
    elseif isKeyPressed("A")  and (coll > 1)  then
        addCentralForce(Player, {-3, 0, 0}, "local")
        playSteepSounds()
    elseif isKeyPressed("D")  and (coll > 1)  then
        addCentralForce(Player, {3, 0, 0}, "local")
        playSteepSounds()
    else isPlaying = false end
end


function charRun()
    if isKeyPressed("LSHIFT") then
        duration = {25,25,25}
        walkSpeed = 8
        else
        duration = {30,30,30}
        walkSpeed = 4
    end
end

Re: Playing random sounds

Is the charRun() function being called under the onSceneUpdate() function?

Re: Playing random sounds

Hi Tutorial Doctor yes the charRun() is being called under the onSceneUpdate() function, this is maybe a logic problem, perhaps theres a better way for making the run function, i tried a "while exp do block end" but maratis crashed (maybe it was a infinite loop).

Re: Playing random sounds

Argoon wrote:

Hi Tutorial Doctor yes the charRun() is being called under the onSceneUpdate() function, this is maybe a logic problem, perhaps theres a better way for making the run function, i tried a "while exp do block end" but maratis crashed (maybe it was a infinite loop).

Haha! Every time I use a while loop Maratis crashes! haha yeah, I think I get an infinite loop.

I am actually working on a game script template. Was just getting ready to post my second phase on the forum.

Re: Playing random sounds

The duration list contains the duration of each of the 3 walk sounds. It's not a speed parameter.

As there isn't a isSoundOver function,  duration is used so that we can guess when the random sound is over and trigger the next one.

So this sound list must remain constant, or the sounds will be trucated (if duration is set below the real duration) or there will be gaps between sounds (if duration is set above the real duration of the track).

Re: Playing random sounds

Thanks com3D them i will have to live with that small bug until i think of some other way.