LibGDX Tutorial 9: Scene2D Part 2– Actions

9. December 2013

 

In the second part of the LibGDX Scene2D tutorial we will now look at Actions.  Actions are a convenient ( and completely optional! ) way to get your game’s Actors to “do stuff”.

 

Let’s jump straight in to an example:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction;


public class SceneDemo3 implements ApplicationListener {
    
    public class MyActor extends Actor {
        Texture texture = new Texture(Gdx.files.internal("data/jet.png"));
        public boolean started = false;

        public MyActor(){
            setBounds(getX(),getY(),texture.getWidth(),texture.getHeight());
        }
        
        @Override
        public void draw(Batch batch, float alpha){
            batch.draw(texture,this.getX(),getY());
        }
    }
    private Stage stage;
    
    @Override
    public void create() {        
        stage = new Stage();
        Gdx.input.setInputProcessor(stage);
        
        MyActor myActor = new MyActor();
        
        MoveToAction moveAction = new MoveToAction();
        moveAction.setPosition(300f, 0f);
        moveAction.setDuration(10f);
        myActor.addAction(moveAction);
        
        stage.addActor(myActor);
    }

    @Override
    public void dispose() {
    }

    @Override
    public void render() {    
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

 

When you run this example, it will slowly move the jet until it is at the position 300,0.

MoveToActionReduced

 

Much of this code is recycled from the previous Scene2D example, so we will only discuss the new portions, which reside in the create() function:

@Override
public void create() {        
    stage = new Stage();
    Gdx.input.setInputProcessor(stage);
    
    MyActor myActor = new MyActor();
    
    MoveToAction moveAction = new MoveToAction();
    moveAction.setPosition(300f, 0f);
    moveAction.setDuration(10f);
    myActor.addAction(moveAction);
    
    stage.addActor(myActor);
}

Here we create a MoveToAction, which moves the attached Actor to a given position over time.  You set the position to move to with the method setPosition() and the total duration of the action using setDuration().  You assign the action to the Actor using addAction().  All actions are derived from the Action class, while MoveToAction is derived from TemporalAction, which is an action that has a duration.  In addition to MoveToAction, there are a number of others such as MoveByAction, ScaleToAction, ColorAction, DelayAction, RepeatAction, RotateByAction, etc.

 

There is one important thing to be aware of here.  Back in part one of the Scene2D tutorial our custom Actor MyActor overrode the act method.  It is the act() method of Actor that updates all of the Actions connected to an Actor.  Therefore if you create your own Actor class, be sure to call it’s parent’s act() or call each attached Action manually like so:

@Override
public void act(float delta){
    for(Iterator<Action> iter = this.getActions().iterator(); iter.hasNext();){
        iter.next().act(delta);
    }
}

If you run more than one actions like so:

MoveToAction moveAction = new MoveToAction();
RotateToAction rotateAction = new RotateToAction();
ScaleToAction scaleAction = new ScaleToAction(); 

moveAction.setPosition(300f, 0f);
moveAction.setDuration(5f);
rotateAction.setRotation(90f);
rotateAction.setDuration(5f);
scaleAction.setScale(0.5f);
scaleAction.setDuration(5f);

myActor.addAction(moveAction);
myActor.addAction(rotateAction);
myActor.addAction(scaleAction);

stage.addActor(myActor);

 

You will see:

RotateScaleMoveActionReduced

As you can see, all of your actions run concurrently by default.

 

There is one important thing to be aware of.  The draw() method in MyActor we’ve been using until this point is not capable of displaying rotation or scaling by default.  If you wish to enabled scaled/rotated drawing like above, you need to make a minor adjustment to draw(), like so:

 

@Override
public void draw(Batch batch, float alpha){
    batch.draw(texture,this.getX(),getY(),this.getOriginX(),this.getOriginY(),this.getWidth(),
            this.getHeight(),this.getScaleX(), this.getScaleY(),this.getRotation(),0,0,
            texture.getWidth(),texture.getHeight(),false,false);
}

 

Obviously there are going to be many times when you want to delay an action, or run them in sequence.  Fortunately LibGdx supports exactly this.  Say you wanted to scale then rotate then move your Actor, you can accomplish this using a SequenceAction like so:

 

final MyActor myActor = new MyActor();

SequenceAction sequenceAction = new SequenceAction();

MoveToAction moveAction = new MoveToAction();
RotateToAction rotateAction = new RotateToAction();
ScaleToAction scaleAction = new ScaleToAction(); 

moveAction.setPosition(300f, 0f);
moveAction.setDuration(5f);
rotateAction.setRotation(90f);
rotateAction.setDuration(5f);
scaleAction.setScale(0.5f);
scaleAction.setDuration(5f);

sequenceAction.addAction(scaleAction);
sequenceAction.addAction(rotateAction);
sequenceAction.addAction(moveAction);


myActor.addAction(sequenceAction);

stage.addActor(myActor);

 

Simply add all the actors to the SequenceAction, then one will run, followed by the next then the next.

By statically importing Actions, like so:

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;

You can also chain actions, so it’s possible to express the above action like:

myActor.addAction(sequence(scaleTo(0.5f,0.5f,5f),rotateTo(90.0f,5f),moveTo(300.0f,0f,5f)));
stage.addActor(myActor);

 

Or run in parallel, like so:

myActor.addAction(parallel(scaleTo(0.5f,0.5f,5f),rotateTo(90.0f,5f),moveTo(300.0f,0f,5f)));
stage.addActor(myActor);

There are several other actions, such as Int or FloatAction, that allow you to modify a value over time, DelayAction for running an action, um, after a delay, RepeatAction, for performing an Action over and over.  However, they all follow the same basic layout, so you should be able to figure them out easily at this point.  One last thing to point out, all Actions are poolable.  This means you can keep a pool of actions instead of allocating them over and over.  Here is one such example of a Pool of MoveToActions:

final MyActor myActor = new MyActor();
Pool<MoveToAction> actionPool = new Pool<MoveToAction>(){
    protected MoveToAction newObject(){
        return new MoveToAction();
    }
};

MoveToAction moveAction = actionPool.obtain();
moveAction.setDuration(5f);
moveAction.setPosition(300f, 0);

myActor.addAction(moveAction);

stage.addActor(myActor);

 

You can also have an action simply be code.  Consider the above example, let’s say you wanted to log when the MoveToAction was complete.  You could accomplish this by doing the following:

myActor.addAction(sequence(moveAction,
        run(new Runnable(){
            @Override
            public void run() {
                Gdx.app.log("STATUS", "Action complete");
            }
            
})));

 

A Runnable action simply runs the code specified in the run method when, um, run. That’s about it for Actions.  On their own they are pretty simply, but can easily be chained to create very complex interactions.

Programming , ,




Using LibGDX in IntelliJ with Gradle

1. December 2013

 

I make no effort to disguise my dislike for Eclipse yet when working with LibGDX Eclipse is the path of least resistance. Fortunately there are other IDEs out there that can work with LibGDX, IntelliJ is my favorite of the options available. 

 

First off, you should be aware that there are currently some key limitations with the Gradle install.  Right now there is no support for GWT ( HTML5 ) or iOS projects.  So if those targets are important you should stick with Eclipse for now.

 

OK, let’s jump right in.  There are a couple things you need to have installed already.  First is a Java JDK, the second is the Android SDK ( not the ADT version! ).  I am not going into detail about how to install these, I simply assume you already have.  If you haven’t already, be sure to download and install IntelliJ IDEA, the free version has everything you need.

 

Installing the template

 

Now you need the LibGDX Gradle Template.  If you have git installed and configured ( you should! ) you can clone the template.  Open a command prompt or teminal, change to the directory you want your project to reside and run the command:

git clone https://github.com/libgdx/libgdx-gradle-template.git

It should run like so:

image

 

Alternately, you can download from github as a zip archive, download and then extract the contents to where you want the project to reside.

 

Now we will install gradle, this process is entirely automated.  In an elevated permission command prompt, change into the directory you just cloned/copied.  Now run the command:

gradlew clean

This will take a bit of time as it downloads and configured gradle and all the dependencies on your project.  Ideally you will see:

image

Now let’s make sure things worked right.  Run the command

gradlew desktop:run

 

Assuming everything went right, you should see:

image

 

Now generate a Intellij project.  Run the command

gradlew idea

This will create an IntelliJ project file with a .ipr extension.

image

 

Configuring IntelliJ IDEA

 

Load IntelliJ IDEA.

At the Quick Start Window, select Open Project

image

 

Navigate to the IPR file then select OK.

image

 

Configure the desktop project

 

Your Project should ( after you click the Project Tab ), look like this:

image

 

Let’s configure the desktop project first.  Select desktop in the project view and hit F4 or right click and select Open Module Settings:

image

 

Since you’ve never configured a JDK, you need to do that first.  In the future you shouldn’t have to do this step.  In the resulting dialog, select Project, then New… on the right side:

image

 

Select JDK in the drop down.  In the next dialog, navigate to and select the directory where you installed the Java JDK, then click OK.

image

 

Now that the Desktop project is configured, we need to create a Run or Debug configuration.  In the Run menu, select either Run… or Debug…

image

 

A menu will pop up, select Edit Configurations…

image

 

In the next dialog, click the + icon:

image

 

In the drop down, select Application:

image

 

Now we need to fill out the form.  You can optionally name your configuration, I went with Debug Desktop.  Next select “Use Classpath of module” and select Desktop.  In working directory, choose the assets folder in the Android project.  Click the … button to the right of Main Class and choose DesktopLauncher.  Finally click Apply then Debug.

image

 

If everything went right you should see:

image

 

Configure the Android Project

 

Now lets take a look at configuring the Android project, it’s a very similar process.

Right Click the Android project and select Open Module Settings.

Select Project, New->Android SDK

image

 

Browse to where you installed the Android SDK then click OK:

image

Pick whatever Java version and Android target you want.  Keep in mind, you need to install the SDKs as part of the Android SDK installation process:

image

 

Click OK, then Apply.

 

Now you can create a Debug or Run configuration for Android.  Select Run->Debug… or Run->Run…

Select Edit Configuration…

Click the + Icon, then select Android Application:

image

 

Now configure your run/debug configuration.  Name it, select Android from the Module pull down, pick what you want to target ( run the emulator vs run on a device ).  Finally click apply then Debug.

image

 

Once you’ve created a Run configuration, you can run your various different projects using this pull down:

image

 

 

Renaming your project

 

It is possible there is a much easier way to do this as part of the Gradle process ( I am certainly no Gradle expert! ) but once you have your project running, you probably want to rename it to something you want.  This means altering directories to match your new naming convention.  IntelliJ makes this fairly simple.

 

In the Project setting, select the Gear icon, then disable Compact Empty Middle Packages.

image

 

 

In this case, instead of com.badlogic.gradletest, I want it to be com.gamefromscratch.gradletest.

In the core project, select badlogic, right click and select Refactor->Rename…

image

 

Select Rename All

image

 

Select your new name, then click Refactor:

image

 

Now repeat the process in the Android folder, select and refactor badlogicgames.

image

 

This time select Rename Directory

image

Once again select the new value you want then click Refactor.

 

Finally locate AndroidManifest.xml and update the package name there as well

image

 

 

A world of note, refactoring wont update your project Run Configuration.  If you rename the project after creating a Run Configuration, you will see:

image

 

This is easily fixed, simply select Run->Edit Configurations:

image

 

Select your Desktop configuration and updated the Main Class to your newly renamed value:

image

 

… now you are up and running in IntelliJ.  It’s a bit more work, but certainly worth it in the end, especially if you dont need GWT or iOS support.  Hopefully those get added soon!

Programming , , ,




LibGDX Tutorial 9: Scene2D Part 1

27. November 2013

 

In this section we are going to take a look at the Scene2D library.  The first thing you need to be aware of is scene2d is entirely optional!  If you don’t want to use it, don’t.  All the other parts, except the bits built over Scene2D, will continue to work just fine.  Additionally if you want to use Scene2D for parts of your game ( such as a HUD overlain over your game ) you can.

 

So, what is scene2D?  In a nutshell, it’s a 2D scene graph.  So you might be asking “what’s a scene graph?”.  Good Question!  Essentially a scene graph is a data structure for storing the stuff in your world.  So if your game world is composed of dozens or hundreds of sprites, those sprites are stored in the scene graph.  In addition to holding the contents of your world, Scene2D provides a number of functions that it performs on that data.  Things such as hit detection, creating hierarchies between game objects, routing input, creating actions for manipulating a node over time, etc.

 

You can think of Scene2D as a higher level framework for creating a game built over top of the LibGDX library.  Oh it also is used to provide a very good UI widget library… something we will discuss later.

 

The object design of Scene2D is built around the metaphor of a play ( or at least I assume it is ).  At the top of the hierarchy you have the stage.  This is where your play (game) will take place.  The Stage in turn contains a Viewport… think of this like, um… camera recording the play ( or the view point of someone in the audience ).  The next major abstraction is the Actor, which is what fills the stage with… stuff.  This name is a bit misleading, as Actor doesn’t necessarily mean a visible actor on stage.  Actors could also include the guy running the lighting, a piece of scenery on stage, etc.  Basically actors are the stuff that make up your game.  So basically, you split your game up into logical Scenes ( be it screens, stages, levels, whatever makes sense ) composed of Actors.  Again, if the metaphor doesn’t fit your game, you don’t need to use Scene2D.

 

So, that’s the idea behind the design, let’s look at a more practical example.  We are simply going to create a scene with a single stage and add a single actor to it.

It’s important to be using the most current version of LibGDX, as recent changes to Batch/SpriteBatch will result in the following code not working!

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;

public class SceneDemo implements ApplicationListener {
    
    public class MyActor extends Actor {
        Texture texture = new Texture(Gdx.files.internal("data/jet.png"));
        @Override
        public void draw(Batch batch, float alpha){
            batch.draw(texture,0,0);
        }
    }
    
    private Stage stage;
    
    @Override
    public void create() {        
        stage = new Stage(Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),true);
        
        MyActor myActor = new MyActor();
        stage.addActor(myActor);
    }

    @Override
    public void dispose() {
        stage.dispose();
    }

    @Override
    public void render() {    
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

 

 

Also note, I also added the jet image I used in earlier examples to the assets folder as a file named jet.png.  See the earlier tutorials if you are unsure of how to do this.  When you run the application you should see:

image

 

As you can see it’s fairly simple process working with Stage2D.  We create an embedded Actor derived class named MyActor.  MyActor simply loads it’s own texture from file.  The key part is the draw() method.  This will be called every frame by the stage containing the actor.  It is here you draw the actor to the stage using the provided Batch.  Batch is the interface that SpriteBatch we saw earlier implements and is responsible for batching up drawing calls to OpenGL.  In this example we simply draw our Texture to the batch at the location 0,0.  Your actor could just as easily be programmatically generated, from a spritesheet, etc.  One thing I should point out here, this example is for brevity, in a real world scenario you would want to manage things differently, as every MyActor would leak it’s Texture when it is destroyed!

 

In our applications create() method we create our stage passing in the app resolution.  The true value indicates that we want to preserve our devices aspect ratio.  Once our stage is created, we create an instance of MyActor and add it to the stage with a call to stage.addActor().  Next up in the render() function, we clear the screen then draw the stage by calling the draw() method.  This in turn calls the draw() method of every actor the stage contains.  Finally you may notice that we dispose of stage in our app’s dispose() call to prevent a leak.

 

So, that is the basic anatomy of a Scene2D based application.  One thing I didn’t touch upon is actually having actors do something or how you would control one.  The basic process is remarkably simple with a couple potential gotchas.  Let’s look at an updated version of this code, the changes are highlighted:

 

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Touchable;

public class SceneDemo2 implements ApplicationListener {
    
    public class MyActor extends Actor {
        Texture texture = new Texture(Gdx.files.internal("data/jet.png"));
        float actorX = 0, actorY = 0;
        public boolean started = false;

        public MyActor(){
            setBounds(actorX,actorY,texture.getWidth(),texture.getHeight());
            addListener(new InputListener(){
                public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
                    ((MyActor)event.getTarget()).started = true;
                    return true;
                }
            });
        }
        
        
        @Override
        public void draw(Batch batch, float alpha){
            batch.draw(texture,actorX,actorY);
        }
        
        @Override
        public void act(float delta){
            if(started){
                actorX+=5;
            }
        }
    }
    
    private Stage stage;
    
    @Override
    public void create() {        
        stage = new Stage();
        Gdx.input.setInputProcessor(stage);
        
        MyActor myActor = new MyActor();
        myActor.setTouchable(Touchable.enabled);
        stage.addActor(myActor);
    }

    @Override
    public void dispose() {
    }

    @Override
public void render() {    
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

 

When you run it you will see:

scene2

Click the jet sprite and it’s action will start.  Let’s take a closer look at the code now.

 

Let’s start with the changes we made to the MyActor class.  The most obvious change you will see is the addition of a constructor.  I did this so I could add an event listener to our actor, that works a lot like event listeners we worked with earlier when dealing with input.  This one however passes an InputEvent class as a parameter which contains the method getTarget(), which is the Actor that was touched.  We simply cast it to a MyActor object and set the started boolean to true.  One other critical thing you may notice is the setBounds() call.  This call is very important!  If you inherit from Actor, you need to set the bounds or it will not be click/touch-able!  This particular gotcha cost me about an hour of my life.  Simply set the bounds to match the texture your Actor contains.  Another thing you may notice is a lot of the examples and documentation on Actor event handling is currently out of date and there were some breaking changes in the past!

 

Other than the constructor, the other major change we made to MyActor was the addition of the act() method.  Just like with draw(), there is an act() method that is called on every actor on the stage.  This is where you will update your actor over time.  In many other frameworks, act would instead be called update().  In this case we simply add 5 pixels to the X location of our MyActor each frame.  Of course, we only do this once the started flag has been set.

 

In our create() method, we made a couple small changes.  First we need to register an InputProcessor.  Stage implements one, so you simply pass the stage object to setInputProcessor().  As you saw earlier, the stage handles calling the InputListeners of all the child actors.  We also set the actor as Touchable, although I do believe this is the default behavior.  If you want to make it so an actor cannot be touched/clicked, pass in Touchable.disabled instead.  The only other change is in the render() method, we now call stage.act() passing in the elapsed time since the previous frame.  This is is what causes the various actors to have their act() function called.

 

Scene2D is a pretty big subject, so I will be dealing with it over several parts.

Programming , ,




GameMaker Standard is now free... I think

25. November 2013

The standard edition of the popular GameMaker software has just gone free, a 50$ savings.  As was mentioned in this reddit post as well as this blog post if you update to the latest beta channel, you get the opportunity to upgrade to Standard from Free edition for free.  However if you check out the forums a fair number of people seem to be having issues, mostly existing customers it would appear.  Also, for reasons I don’t quite understand, this opportunity is currently unavailable for people using GameMaker from Steam.

 

If you’ve never heard of it, GameMaker is a higher level game development system aimed at the beginner segment for creating 2D games.  It offers a drag and drop environment and is controlled using GML, Game Makers custom scripting language.  Somewhat recently YoYo released a native compiler that massively increases GML performance, however this is not a standard feature. The primary difference between the free version and the standard version is the free version forced a splash screen on you and greatly limited the number of resources your game could use.  In addition to the free release of Standard, Tizen support is also free, most likely to correspond with their Tizen contest.

 

If you view GameMaker as just a toy, keep in mind it has been used to create a number of very successful titles including Spelunky and Hotline Miami.  On the other hand, Yoyo Games have also pulled some mind numbingly stupid mistakes.  GameMaker may not be for everyone, myself included, but for many it is a great option, especially if you aren’t primarily a programmer.

 

So, if you want to check out GameMaker, now is a good time… just don’t do it on Steam!  What’s odd is the complete lack of formal announcement from YoYo.




LibGDX Tutorial 8: Audio

19. November 2013

 

This section is going to be rather small because, well frankly, LibGDX makes audio incredibly easy.  Unlike previous tutorials, this one is going to contain a number of snippets.  LibGDX supports 3 audio formats: ogg, mp3 and wav.  MP3 is a format that is mired in legal issues, while WAV is a rather large ( file size ) format, leaving OGG as often the best choice.  That said, when it comes to being broadly supported ( especially in browsers ), Ogg can have issues.  This of course is why multiple formats exist and continue to be used!

Playing Sound Effects

 

Loading a sound file is trivial.  Like you did earlier with fonts or graphic formats, you need to add the files to assets folder in the android project folder.  Like earlier, I followed convention and put everything in the data subdirectory like so:

wyabq5gw

 

As you can see, I added a file of each format, mp3.mp3, ogg.ogg and wav.wav.

 

Loading any of these files is incredibly simple:

Sound wavSound = Gdx.audio.newSound(Gdx.files.internal("data/wav.wav"));
Sound oggSound = Gdx.audio.newSound(Gdx.files.internal("data/ogg.ogg"));
Sound mp3Sound = Gdx.audio.newSound(Gdx.files.internal("data/mp3.mp3"));

This returns a Sound object using the specified file name.  Once you have a Sound, playing is trivial:

wavSound.play();

You also have the option of setting the play volume when calling play, such as:

oggSound.play(0.5f);

This plays the oggSound object at 50% volume for example.

 

In addition to play() you can also loop() to well, loop a Sound continuously.  When you play a sound it returns an id that you can use to interact with the sound.  Consider:

long id = mp3Sound.loop();
Timer.schedule(new Task(){
   @Override
   public void run(){
      mp3Sound.stop(id);
      }
   }, 5.0f);

 

Here you start an mp3 file looping, which returns an id value.  Then we schedule a task to run 5 seconds later to stop the sound from playing.  Notice how in the call to stop() an id is passed?  This allows you to manage a particular instance of a sound playing.  This is because you can play the same Sound object a number of times simultaneously.  One important thing to be aware of, Sound objects are a managed resource, so when you are done with them, dispose().

wavSound.dispose();
oggSound.dispose();
mp3Sound.dispose();

 

Once you have a sound, there are a number of manipulations you can do.  You can alter the pitch:

long id = wavSound.play();
wavSound.setPitch(id,0.5f);

 

The first parameter is the sound id to alter, the second value is the new pitch ( speed ).  The value should be > 0.5 and < 2.0.  Less than 1 is slower, greater than 1 is faster.

You can alter the volume:

long id = wavSound.play();
wavSound.setVolume(id,1.0f);

 

Once again, you pass the id of the sound, as well as the volume to play at.  A value of 0 is silent, while 1 is full volume.  As well you can set the Pan ( stereo position ), like so:

long id = wavSound.play();
wavSound.setPan(id, 1f, 1f);

In this case the parameters are the sound file id, the pan value ( 1 is full left, 0 is center, –1 is full right ) as well as the volume.  You can also specify the pitch, pan and volume when calling play() or loop().  One important note, none of these methods are guaranteed to work on the WebGL/HTML5 backend.  Additionally file format support varies between browsers ( and is very annoying! ).

 

Streaming music

 

In addition to playing sound effects, LibGDX also offers support for playing music ( or longer duration sound effects! ).  The big difference is LibGDX will stream the effect in this case, greatly lowering the demands on memory. This is done using the Music class.  Fortunately it’s remarkably simple:

Music mp3Music = Gdx.audio.newMusic(Gdx.files.internal("data/RideOfTheValkyries.mp3"));
mp3Music.play();

 

And that’s all you need to stream an audio file.  The controls are a bit different for a Music file.  First off, there is no id, so this means you can play multiple instances of a single Music file at once.  Second, there are a series of VCR style control options.  Here is a rather impractical example of playing a Music file:

 

Music mp3Music = Gdx.audio.newMusic(Gdx.files.internal("data/RideOfTheValkyries.mp3"));
mp3Music.play();
mp3Music.setVolume(1.0f);
mp3Music.pause();
mp3Music.stop();
mp3Music.play();
Gdx.app.log("SONG",Float.toString(mp3Music.getPosition()));

 

After our Music file is loaded, we start it, then set the volume to 100%.  Next we pause, then stop, then play our music file again.  As you can see from the log() call, you can get the current playback position of the Music object by calling getPosition().  This returns the current elapsed time into the song in seconds.  You may be wondering exactly what the difference is between pause() and stop()?  Calling play() after pause() will continue playing the song at the current position.  Calling play() after calling stop() will restart the song.

Once again, Music is a managed resource, so you need to dispose() it when done or you will leak memory.

 

Recording and playing PCM audio

 

LibGDX also has the ability to work at a lower level using raw PCM data.  Basically this is a short (16bit) or float (32bit) array of values composing the wavform to play back.  This allows you to create audio effects programmatically.  You can also record audio into PCM form.  Consider the following example:

AudioDevice playbackDevice = Gdx.audio.newAudioDevice(44100, true);
AudioRecorder recordingDevice = Gdx.audio.newAudioRecorder(44100, true);
short[] samples = new short[44100 * 10]; // 10 seconds mono audio
recordingDevice.read(samples, 0, samples.length);
playbackDevice.writeSamples(samples, 0, samples.length);
recordingDevice.dispose();
playbackDevice.dispose();

 

This example creates an AudioDevice and AudioRecorder.  In both functions you pass the desired sampling rate ( 44.1khz is CD audio quality ) as well as a bool representing if you want mono ( single channel ) or stereo ( left/right ) audio.  Next we create an array to record our audio into.  In this example, we want 10 seconds worth of audio at the 44.1khz sampling rate.  We then record the audio by calling the read() method of the AudioRecorder object.  We pass in the array to write to, the offset within the array to start at and finally the total sample length.  We then playback the audio we just recording by calling writeSamples, using the exact same parameters.  Both AudioDevice and AudioRecorder are managed resources and thus need to be disposed.

 

There are a few very important things to be aware of.  First, PCM audio is NOT available on HTML5.  Second, if you are recording in Stereo, you need to double the size of your array.  The data in the array for a stereo waveform is interleaved.  For example, the first byte in the array is the very first float of the left sound channel, then the next float is the first value in the right channel, the next float is the second float of the left sound channel, and so on.

Programming , ,