OpenAL tutorial using ALUT

Source: The OpenAL Utility Toolkit.pdf

I will be using OpenAL Utility Toolkit in this example. You can say OpenAL is a 3D audio library. It can be used efficiently in games and many other applications that requires sound.

Getting Started

To play a PCM data (e.g wave file), we first create some buffers, fill in sound from filesystem to these buffers, attach these buffers to different sources. If we like position, move the listeners and sources and finally play the sources. You can think sources are sound generating sources, which can be situated in different places on the 3D space, listeners as ears. Lets see a simple code (ignoring listeners and sources) to see this.

#include <AL/al.h>
#include <AL/alc.h>
#include <AL/alut.h>
#include <stdio.h>

// gcc -o simplealut simplealut.c `pkg-config --libs freealut`
#define FILENAME "sample.wav"

int main(int argc, char **argv)

    ALuint buffer, source;
    ALuint state;

    // Initialize the environment
    alutInit(0, NULL);

    // Capture errors

    // Load pcm data into buffer
    buffer = alutCreateBufferFromFile(FILENAME);

    // Create sound source (use buffer to fill source)
    alGenSources(1, &source);
    alSourcei(source, AL_BUFFER, buffer);

    // Play

    // Wait for the song to complete
    do {
        alGetSourcei(source, AL_SOURCE_STATE, &state);
    } while (state == AL_PLAYING);

    // Clean up sources and buffers
    alDeleteSources(1, &source);
    alDeleteBuffers(1, &buffer);

    // Exit everything

    return 0;

Above example is a simple example to play a file called “sample.wav” from filesystem.

We first initialize the environment, get some errors if any, load file from filesystem into buffer, create source using this buffer and finally play. We track AL_PLAYING state so that the alSourcePlay does not exit prematurely. Tracking AL_PLAYING seems a costly process (memory used). Previously I used alutSleep to let sound play, but I could not determine how long to do that.  Anyway, this is still a good example where we can add velocity and positions to our sources and listeners to create doplers effect.

Good Luck.


2 Responses to “OpenAL tutorial using ALUT”

  1. Beymer Bevill Says:

    Thanks! I was about to give up on OpenAL … none of the online tutorials seemed to work!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s