Skip to content

5. Playing Audio

João Alves edited this page Jan 1, 2022 · 12 revisions

Introduction

This section explains how to play sounds using the Pixel framework Audio Engine.

The current Audio Engine implementation uses OpenAL which is a cross-platform library that provides an easy-to-use API to play sounds using native calls.

📖 Want to jump right in? Learn with a code example.

Modules

To use the implementations refered on this section you must include the following module(s):

  • pixel-core

Playing sound

The first thing to do is to import an Audio file (currently Pixel supports Vorbis '.ogg' format), which can be done using the ContentManager class:

// ...
private Sound sound;
// ...
@Override
public void load() {
    // ...
    sound = content.load("<your_sound_path>", Sound.class);
    // ...
}

Since the current audio implementation is a simple wrapper to the OpenAL native API, the AudioEngine class is a singleton. To play the Sound instance loaded in the previous step, all you need to do is to call the function play() from the AudioEngine:

// this variation of the 'play' function allows to assign a loop property, which if set to true as this
// example shows, will play the sound until manually stopped.
AudioEngine.play(sound, true);

Notice that the sound instance is a reference to a native buffer, you can use it as a reference to the audio you are currently playing.

To stop a sound from playing, you can call the stop() function:

AudioEngine.stop(sound);

To simply pause a sound from playing:

AudioEngine.pause(sound);

If you want to know at what time position (seconds) the audio is at:

float seconds = AudioEngine.getTimePosition(sound);
// note that there is also a `setTimePosition()` function.

Sound attributes

In addition to the basic functionality (play/pause/stop sounds) you can also modify certain properties of the sound you're playing such as the gain, pitch, position, timePosition and velocity.

Each of the properties can be changed directly using their respective functions on the AudioEngine class. Notice that these properties can be changed while the audio is already being played.

Example of pitch definition:

AudioEngine.setPitch(sound, 0.5f);

Positional audio

One of the cool features of the AudioEngine is the ability pan audio (if stereo is available) which can create cool audio effects such as virtually positioning the audio source to create a better audio experience (for example, playing a sound only on the left speaker, or reducing the volume as the distance grows between the player and the audio source).

This can be done using the position attribute as follows:

// this function call will set the audio source to play only the left speaker
AudioEngine.setPosition(sound, -1, 0); 
  • The setPosition() has 2 function variations (sound, x, y) and (sound, x, y, z).
  • Check here for a positional audio example.
Clone this wiki locally