Book Image

Getting Started with C++ Audio Programming for Game Development

By : David da L Gouveia
Book Image

Getting Started with C++ Audio Programming for Game Development

By: David da L Gouveia

Overview of this book

Audio plays a fundamental role in video games. From music to sound effects or dialogue, it helps to reinforce the experience, convey the mood, and give feedback to the player. Presently, many games have achieved commercial success by incorporating game sounds that have enhanced the user experience. You can achieve this in your games with the help of the FMOD library. This book provides you with a practical guide to implementing the FMOD toolkit in your games. Getting Started with C++ Audio Programming for Game Developers is a quick and practical introduction to the most important audio programming topics that any game developer is expected to know. Whether you need to play only a few audio files or you intend to design a complex audio simulation, this book will help you get started enhancing your game with audio programs. Getting Started with C++ Audio Programming for Game Developers covers a broad range of topics – from loading and playing audio files to simulating sounds within a virtual environment and implementing interactive sounds that react to events in the game. The book starts off with an explanation of the fundamental audio concepts, after which it proceeds to explain how to use the FMOD Ex library, how to implement a 3D audio simulation, how to use the FMOD Designer toolkit, and how best to work with multi-layered sounds with complex behaviors attached to them. The final part of the book deals with working with audio at a much lower level by manipulating audio data directly. This book will provide you with a good foundation so that you can successfully implement audio into your games and begin pursuing other advanced topics in audio programming with confidence.
Table of Contents (13 chapters)
Getting Started with C++ Audio Programming for Game Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Audio is certainly one of the most powerful tools at our disposal when it comes to making the players feel something from a video game. Audio can serve many different purposes in video games, such as giving feedback with sound effects, increasing immersion with ambient tracks, telling stories with recorded speech, or conveying all kinds of emotions through background music.

Video games have been making use of sound since their earliest days. For instance, the 1972 classic, Pong, used a beep sound effect to provide feedback whenever the ball collided with something, with different pitches used to distinguish between collisions with the walls, collisions with the paddles, or the ball leaving the game court.

Space Invaders, on the other hand, made a very clever use of its rudimentary background music by progressively increasing the speed of the song as the danger of the alien invasion drew closer, thus enhancing the feelings of tension within the player. Studies have shown that gamers that played the game without sound did not feel the same sense of urgency, and their heart rates did not rise like the ones that played the game with the sound turned on.

Since those days, there have been many advances in technology, which allowed audio in games to evolve considerably. Most games began using recorded audio instead of crude synthesized tones, and new techniques such as 3D audio now allow the players to feel like the sound is coming from all around them and interacting with the game environment.

Music has also played a very important role in video games. The popular Final Fantasy games owe a great portion of their emotional impact to the sweeping, cinematic soundtracks composed by Nobuo Uematsu. The most memorable scenes in the series would have not been the same without the music that accompanied them.

Many developers and composers have also looked into ways of making the music react to the game play. For example, starting with Monkey Island 2, LeChuck's Revenge, every graphic adventure game that LucasArts created uses a custom interactive music system called iMUSE, which among other features, allows seamless musical transitions between themes as the player moves from one room to another.

There are even games that incorporate audio concepts directly into their main gameplay mechanics, such as the songs that the player has to memorize and play in The Legend of Zelda: Ocarina of Time, and games that revolve entirely around sound, with the most popular examples being rhythm games, such as PaRappa the Rapper, Dance Dance Revolution, or Guitar Hero.

However, despite being such an important part of video games, many game development books skim through the subject of audio programming. Even the ones that dedicate a chapter to audio, often only teach you the very basics, such as loading and playing audio files, or use outdated audio engines instead of the ones used by the industry nowadays. Additionally, other game development topics, such as graphics, physics, or artificial intelligence tend to be more enticing to beginner level game developers and learning about audio becomes less of a priority.

The main goal of this book is to give you a crash course on audio programming for games by using a popular and well-established audio engine, and covering the subject from several different levels of abstraction. It is my hope that this approach will give you enough knowledge to implement most of the audio features that are normally required for a video game, and form a foundation so that you may pursue other topics that are more advanced.

What this book covers

Chapter 1, Audio Concepts, covers some of the most important audio concepts, such as sound waves, analog and digital audio, multi-channel audio, and audio file formats.

Chapter 2, Audio Playback, shows how to use FMOD to load and play audio files, and how to begin creating a simple audio manager class.

Chapter 3, Audio Control, shows how to control the playback and parameters of a sound, and how to group sounds into categories and control them simultaneously.

Chapter 4, 3D Audio, covers the most important concepts of 3D audio, such as positional audio, reverberation, obstruction/occlusion, along with a few DSP effects.

Chapter 5, Intelligent Audio, provides an overview of high-level sound design using the FMOD Designer tool, with examples of how to create adaptive and interactive sound events and music.

Chapter 6, Low-level Audio, provides basic information on how to work with audio at a very low-level, by manipulating and writing audio data directly.

What you need for this book

For this book, you will need the following software:

  • C++ IDE: Instructions are provided for Microsoft Visual Studio, but you should be able to use any C++ IDE or compiler. The Express version of Visual Studio is free and can be downloaded from the Microsoft website.

  • FMOD Ex: Needed for chapters 2 - 4, and 6 and can be downloaded for free from www.fmod.org.

  • FMOD Designer: Needed for chapter 5. Can be downloaded for free from www.fmod.org.

  • SFML: All of the code samples on the website also use SFML (Version 2.0) to handle other tasks, such as window management, graphics, and input handling. Free download from www.sfml-dev.org.

Who this book is for

This book is oriented towards C++ game developers who have little or no experience with audio programming and would like a quick introduction to the most important topics required to integrate audio into a game.

You will need an intermediate knowledge of C++ to be able to follow the code examples in the book, including an understanding of basic C++ Standard Library features, such as strings, containers, iterators, and streams. Some game programming experience is also recommended, but not mandatory.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Notice that the function returns the system object through a parameter."

A block of code is set as follows:

#include <math.h>

float ChangeOctave(float frequency, float variation) {
  static float octave_ratio = 2.0f;
  return frequency * pow(octave_ratio, variation);
}
float ChangeSemitone(float frequency, float variation) {
  static float semitone_ratio = pow(2.0f, 1.0f / 12.0f);
  return frequency * pow(semitone_ratio, variation);
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

#include <SFML/Window.hpp>
#include "SimpleAudioManager.h"

int main() {
  sf::Window window(sf::VideoMode(320, 240), "AudioPlayback");
  sf::Clock clock;
  
  // Place your initialization logic here
  SimpleAudioManager audio;
  audio.Load("explosion.wav");
  
  // Start the game loop
  while (window.isOpen()) {
    // Only run approx 60 times per second
    float elapsed = clock.getElapsedTime().asSeconds();
    if (elapsed < 1.0f / 60.0f) continue;
    clock.restart();
    sf::Event event;
    while (window.pollEvent(event)) {
      // Handle window events
      if (event.type == sf::Event::Closed) 
        window.close();

      // Handle user input
      if (event.type == sf::Event::KeyPressed &&
          event.key.code == sf::Keyboard::Space)
        audio.Play("explosion.wav");
    }
    // Place your update and draw logic here
    audio.Update(elapsed);
  }
  // Place your shutdown logic here
  return 0;
}

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "For all the steps that follow, make sure that the Configuration option is set to All Configurations."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.