Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

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:



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 ="data/wav.wav"));
Sound oggSound ="data/ogg.ogg"));
Sound mp3Sound ="data/mp3.mp3"));

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

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

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(){
   public void run(){
   }, 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().



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

long id =;


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 =;


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.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 ="data/RideOfTheValkyries.mp3"));;


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 ="data/RideOfTheValkyries.mp3"));;


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 =, true);
AudioRecorder recordingDevice =, true);
short[] samples = new short[44100 * 10]; // 10 seconds mono audio, 0, samples.length);
playbackDevice.writeSamples(samples, 0, samples.length);


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 , ,

13. November 2013




As you may be able to tell by the title… or the picture above, I am about to depart to somewhere a heck of a lot warmer than Toronto currently is!  It’s only a short vacation though, so expect posts to resume early next week.


Until then, see you at the beach!

Totally Off Topic

12. November 2013


I know this is a release that many people have been waiting for, the Unity version with out of the box support for 2D.


So, what’s in this release:

  • 2D, including tools for making sprites, scene population, physics and animation. Pro version includes automatic texture atlas generation and alpha cut outs.
  • Mecanim improvements. New keyframe based dopesheet, drive blend shapes, and perhaps most import, full scriptability of the animation system.
  • MonoDevelop 4.0.1 support.  MonoDevelop 4 is loads better, so this is nice.
  • iOS new features include Game Controller support, OpenGL ES3
  • Windows 8 support for the trial api for try before buy enabling your game
  • Support for Plastic SCM version control software
  • Pro Only feature – nav mesh can now be altered at runtime
  • A lot of smaller improvements


You can see the new 2D workflow in the video below:


You can download Unity 4.3 right here for free.

News ,

6. November 2013


Now we are going to look quickly at using a camera, something we haven’t used in any of the prior tutorials.  Using a camera has a couple of advantages.  It gives you an easier way of dealing with device resolution as LibGDX will scale the results up to match your device resolution.  It also makes it easier to move the view around when your scene is larger than a single screen.  That is exactly what we are going to do in the code example below.


I am using a large ( 2048x1024 ) image that I obtained here.


Alright, now the code:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationListener;

import com.badlogic.gdx.Gdx;







import com.badlogic.gdx.input.GestureDetector;

import com.badlogic.gdx.input.GestureDetector.GestureListener;

import com.badlogic.gdx.math.Vector2;

public class CameraDemo implements ApplicationListener, GestureListener {

private OrthographicCamera camera;

private SpriteBatch batch;

private Texture texture;

private Sprite sprite;


public void create() {

   camera = new OrthographicCamera(1280, 720);

   batch = new SpriteBatch();

   texture = new Texture(Gdx.files.internal("data/Toronto2048wide.jpg"));

   texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

   sprite = new Sprite(texture);



   Gdx.input.setInputProcessor(new GestureDetector(this));



public void dispose() {





public void render() {, 1, 1, 1);;







public void resize(int width, int height) {



public void pause() {



public void resume() {



public boolean touchDown(float x, float y, int pointer, int button) {

// TODO Auto-generated method stub

return false;



public boolean tap(float x, float y, int count, int button) {

// TODO Auto-generated method stub

return false;



public boolean longPress(float x, float y) {

// TODO Auto-generated method stub

return false;



public boolean fling(float velocityX, float velocityY, int button) {

// TODO Auto-generated method stub

return false;



public boolean pan(float x, float y, float deltaX, float deltaY) {

   // TODO Auto-generated method stub



   return false;



public boolean zoom(float initialDistance, float distance) {

// TODO Auto-generated method stub

return false;



public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,

Vector2 pointer1, Vector2 pointer2) {

// TODO Auto-generated method stub

return false;




Additionally in I changed the resolution to 720p like so:

package com.gamefromscratch;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;

import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {

   public static void main(String[] args) {

      LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();

      cfg.title = "camera";

      cfg.useGL20 = false;

      cfg.width = 1280;

      cfg.height = 720;

      new LwjglApplication(new CameraDemo(), cfg);



When you run it you will see:



Other then being an image of my cities skyline, its pan-able. You can swipe left or right to pan the image around.


The code is mostly familiar at this point, but the important new line is:

camera = new OrthographicCamera(1280, 720);

This is where we create the camera.  There are two kinds of cameras in LibGDX, Orthographic and Perspective.  Basically an orthographic camera renders what is in the scene exactly the size it is.  A perspective camera on the other hand emulates the way the human eye works, by rendering objects slightly smaller as they get further away.  Here is an example from my Blender tutorial series.







Notice how the far wing is smaller in the perspective render?  That’s what perspective rendering does for you.  In 2D rendering however, 99 times out of 100 you want to use Orthographic.


The values passed to the constructor are the resolution of the camera, the width and height.  In this particular case I chose to use pixels for my resolution, as I wanted to have the rendering at 1280x720 pixels.  You however do not have to… if you are using physics and want to use real world units for example, you could have gone with meters, or whatever you want.  The key thing is that your aspect ratio is correct.  The rest of the code in create() is about loading our image and positioning it about the origin in the world.  Finally we wire up our gesture handler so we can pan/swipe left and right on the image.


The next important call is in render():


This ties our LibGDX camera object to the OpenGL renderer.  The OpenGL rendering process depends on a number of matrix to properly translate from the scene or world to screen coordinates during rendering.  camera.combined returns the camera’s view and projection matrixes multiplied together.  If you want more information about the math behind the scenes you can read here.  Of course, the entire point of the Camera classes is so you don’t have to worry about this stuff, so if you find it confusing, don’t sweat it, LibGDX takes care of the math for you. 

Finally in our pan handler ( huh? ) we have the following code:




You can use translate to move the camera around. Here we move the camera along the X axis by the amount the user swiped. This causes the view of the image to move as the user swipes the screen/pans the mouse. Once you are done modifying the camera, you need to update it. Without calling update() the camera would never move.

There are a number of neat functions in the camera that we don’t use here.  There are functions to look at a point in space, to rotate or even rotate around ( orbit ) a vector.  There are also functions for projecting to and from screen to world space as well as code for ray casting into the scene.  In a straight 2D game though you generally won’t use a lot of this functionality.  We may take a closer look at the camera class later on when we jump to 3D.

Programming , ,

5. November 2013

A bit of bittersweet news today out of Microsoft:

If one thing has become clear as we’ve been working on ID@Xbox, our independent developer self-publishing program for Xbox One, it’s that today’s independent game developers are using middleware to help realize their visions more than ever. Of course, middleware isn’t cheap.
One of the cool things about working at Microsoft is that we have access to pretty amazing resources. For independent developers though, tools like Unity on console can cost quite a bit.

We talked internally at ID@Xbox about ways we could help developers for Xbox One. Many developers we talk to are using Unity today to get up and running quickly, and to be able to harness the power of hardware and realize their creative visions without spending tons of time on technology development. We thought about paying for some developers’ Unity licenses but the more we talked about it, the more we felt paying for some developers’ licenses and not others just didn’t feel right.  

To us, ID@Xbox is about providing a level playing field for all developers. So, we worked with Unity and we’re pleased to announce that, when released in 2014, the Xbox One add-on for Unity will be available at no cost to all developers in the ID@Xbox program, as will special Xbox One-only Unity Pro seat licenses for Xbox One developers in the ID@Xbox program.

Will we devote marketing and promotion to promising looking titles in development? Of course. But we want to make sure the dev who’s working away in Omaha, or Coventry, or Chiba will have the same shot to realize their vision on Xbox One as one of my developer friends we hang out with in Seattle or at a trade show like GDC or Gamescom. Because at the end of the day, we want gamers to pick the hits. That’s what Xbox One is all about: One games store, the best discovery tools on console, and a powerful, equal playing field for all games, from developers big and small.

This announcement is cool for a bunch of reasons. The Unity add-on for Xbox One supports every element of Xbox One, from Kinect to SmartGlass to the impulse triggers of the new controller. Using Unity, developers will be able to take advantage of all aspects of Xbox One, which is rad. More importantly, Unity is available for Windows and Windows Phone too (and yes, the add-on is available at no cost to developers for Windows Phone and Windows 8 store games). So from one base game, developers can ship their games across all Microsoft platforms. For more details on Microsoft’s partnership with Unity, check out this Xbox Wire post from BUILD 2013.

As always, our goal at ID@Xbox and Microsoft remains the same: We want to lower friction for developers on Microsoft platforms to make sure gamers get access to the broadest and deepest library of amazing games on the planet. We’re also excited to work with other middleware and service providers to drive value for independent developers, and we hope to have even more announcements that directly benefit developers.


You can read the entire Microsoft blog post here.  You can also read about it on Unity’s blog here.  Here is a snippet of their announcement below:

Unity and Microsoft will now be working together to bring the Xbox One  deployment add-on to all developers registered with the ID@Xbox program at no cost to the developers. This is huge news and means that everyone that’s part of that program, not just partners to Microsoft Games Studios, will be able to take advantage of Unity to create awesome gaming experiences for the Xbox One. On top of this, a special Xbox One version of the Unity Pro tools are also being made available for these same developers at no cost.

The Xbox One is a powerful platform and we’re building powerful tools to take advantage of all of the features that make it so special like the Kinect and SmartGlass. Production is well underway and is progressing faster than originally anticipated! Very early testing phases will begin soon with a broader beta program in 2014.


In case you have never heard of it, ID@Xbox is Microsoft’s independent developer publishing program.  Of key importance, is probably this piece from the ID@XBox FAQ about who can qualify:

Of course, we’ll be evaluating each developer application individually on its own merits, but in the initial phase of ID@Xbox, we are looking for professional independent game developers who have a proven track record of shipping games on console, PC, mobile, or tablet. We want to ensure your success in your development effort on Xbox One. Developing and publishing a console game is not trivial!

Our longer term plan is that anyone with a retail Xbox One will be able to develop, publish, and sell their game on Xbox Live.


So in a nutshell, you can now get a version of Unity for free supporting Xbox One functionality, including Smartglass, the controller and Kinect if you are a member of ID@Xbox.

Why bittersweet?  This essentially means that chances for an XNA successor is pretty much zero.  Increasingly this means alternatives to Unity are becoming increasingly rare.  Additionally pure hobbyist developers are left in the lurch for now.  Got an Xbox One and want to just play around making games?  You can’t for now.  Again from the FAQ:

Can I use my retail kit as a development kit?

As part of our vision for enabling everyone with an Xbox One to be a creator, we absolutely intend to enable people to develop games using their retail kits. Right now, though, you still need a development kit! We provide two kits to everyone in the registered developer program. Additional kits, if needed, can be purchased.

Bummer, at least for now.


So, if you are an established indie developer, or more specifically an established indie developer working in Unity, this is amazingly good news.  If you however are a hobbyist, especially one hoping for another XNA like SDK for Xbox One this certainly isn’t.  Of course this isn’t to say Microsoft won’t be creating another XNA like development kit, but given this news, I highly doubt it.  They’ve effectively outsourced it to Unity.

Month List

Popular Comments

Black Friday for Game Developers
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

26. November 2015


Each year Black Friday has more and more game development deals.  Each year it also gets earlier and earlier… Black Thursday, Black Wednesday, you name it and of course they are trying to stretch it out with Cyber Monday.  This post is an attempt to capture the Black Friday/Cyber Monday deals most relevant to game developers.  If you know of a applicable sale I missed on this list, please let me know!

I will edit this list as new deals are located.  Have a gamedev deal to announce, email me at, leave a comment below or in this reddit conversation.






3D Coat


YoYo Games






Microsoft Store


Misc PC Manufacturers Black Friday Sales Pages (US Store links)


The Foundry






Smith Micro




CG Axis






Mobile Game Graphics


Game Salad

News, GameDev News, General

blog comments powered by Disqus

Month List

Popular Comments