Basic AL Operation

AL can be used for a variety of audio playback tasks, and is an excellent complement to OpenGL for real-time rendering. A programmer who is familiar with OpenGL will immediately notice the similarities between the two APIs in that they describe their 3D environments using similar methods.

For an OpenGL/AL program, most of the audio programming will be in two places in the code: initialization of the program, and the rendering loop. An OpenGL/AL program will typically contain a section where the graphics and audio systems are initialized, although it may be spread into multiple functions. For OpenAL, initialization normally consists of creating a context, creating the initial set of buffers, loading the buffers with sample data, creating sources, attaching buffers to sources, setting locations and directions for the listener and sources, and setting the initial values for state global to AL.

Example 1. Initialization Example

    
  

Example 2. Initialization Example

      
       

The audio update within the rendering loop normally consists of telling AL the current locations of the sources and listener, updating the environment settings, and managing buffers.

Example 3. Processing Loop

// PlaceCamera -- places OpenGL camera and updates OpenAL listener position and source state
void 3DEnvironemnt:PlaceCamera()
{
   // update OpenGL camera position
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glFrustum(-0.1333, 0.1333, -0.1, 0.1, 0.2, 50.0);

   gluLookAt(listenerPos[0], listenerPos[1], listenerPos[2],
      (listenerPos[0] + sin(listenerAngle)), listenerPos[1], (listenerPos[2] - cos(listenerAngle)),
      0.0, 1.0, 0.0);

   // OpenAL stuff...
   // place listener at camera
   alListener3f(AL_POSITION, listenerPos[0], listenerPos[1], listenerPos[2]);
   float directionvect[6];
   directionvect[0] = (float) sin(listenerAngle);
   directionvect[1] = 0;
   directionvect[2] = (float) cos(listenerAngle);
   directionvect[3] = 0;
   directionvect[4] = 1;
   directionvect[5] = 0;
   alListenerfv(AL_ORIENTATION, directionvect);

   // play phasor if in range, else stop playback
   if (range() < 9)
   {
      alSourcePlay(source[1]);
   } else
   {
      alSourceStop(source[1]);
   }
}