Chapter 4. Sound
Sound is a frequently overlooked part of games. Even in big-name titles, sound design and programming are sometimes left until late in the game development process. This is especially true on mobile devices—the user might be playing the game in a crowded, noisy environment and might not even hear the sounds and music you’ve put into it, so why bother putting in much effort?
However, sound is an incredibly important part of games. When a game sounds great, and makes noises in response to the visible parts of the game, the player gets drawn in to the world that the game’s creating.
In this chapter, you’ll learn how to use iOS’s built-in support for playing both sound effects and music. You’ll also learn how to take advantage of the speech synthesis features built into iOS.
Sound good?[1]
Playing Sound with AVAudioPlayer
Problem
You want to play back an audio file, as simply as possible and with a minimum of work.
Solution
The simplest way to play a sound file is using AVAudioPlayer, which is a class available in the AVFoundation framework. To use this feature, you first need to import the AVFoundation module in each file that uses the AVFoundation classes:
importAVFoundation
You create an AVAudioPlayer by providing it with the location of the file you want it to play. This should generally be done ahead of time, before the sound needs to be played, to avoid playback delays.
In this example, audioPlayer is an optional AVAudioPlayer instance variable:
letsoundFileURL=NSBundle ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access