music file play

edited December 2016 in Library Questions

Hi, have the following problem. I have a tank, that is controlled by the keys. I have found the sound of an engine roaring. BUT, I want it to be played ONLY if the key is pressed.

If I code: If (mouseClicked == true) then mySound.play

Then the sound will be played from the start every time I click the mouse button. What is the right way to do this?

Answers

  • Post a small sample code showing your issue. Ppl will be able to see what have you tried so far and how to improve based on your layout.

    Kf

  • edited December 2016

    Ok, I think I know where the problem lies.

    I check if the sound has to be played in the draw function, it means the sound will be started 30 times a sec which is too much.

    However, I still don't get how to do it right. In general my code looks like this:

    void draw () 
    {
       if (tank.engineMagnitude > 1) {
       movement.play;
       }
    }
    
  • You could do loop() instead of play(). Then when the key is pressed for motion, you let it loop. When the key is released, you will stop the sound. This has to be modified in case you are executing multiple keys at the same time. However, without seeing proper code, I cannot provide any further comments.

    Kf

  • edited December 2016 Answer ✓

    @strinda --

    Some suggestions to try:

    1. call movement.loop() (not .play()) from keyPressed() (not from draw()) as @kfrajer suggests.

    2. if you want to start a play or loop event inside draw, put a guard flag on it that checks whether it is already playing so that it won't be repeatedly called (as you discovered).

      boolean playnow = false;
      
      void draw(){
        if(playnow==false && tank.engineMagnitude > 1){
          movement.play();
          playnow=true;
        }
      }
      void keyPressed(){
        tank.engineMagnitude = 2;
      }
      
  • Ok, will do.

    Thank you for the suggestions! From time to time I get the following error, and I think it is related to sound as it didn't show up until I started playing with it.

    What does it mean?

    ERROR: /node/free: Node id -1 out of range ERROR: /node/free: Node id -1 out of range ERROR: /node/free: Cannot free root node 0 ERROR: /node/free: Cannot free root node 0

Sign In or Register to comment.