Playing Sounds/Audio – AVAudioPlayer

I previously wrote about using Audio Session Services which offers a quick and easy approach for playing short sounds. However, there are a number of limitations, including no control over the volume, playing time is limited to 30 seconds and the only file types supported are AIFF, WAV and CAF.

Sounds with AVAudioPlayer

AVAudioPlayer offers a much wider range of capabilites, including pausing playback, adjusting the volume, tinkering with the playback time (setting and detecting) as well as features for monitoring audio peaks and averages.

The code below shows the basics for setting up a player and playing a sound:

AVAudioPlayer  *player;
NSString       *path;
NSError        *error;
// Path the audio file
path = [[NSBundle mainBundle] pathForResource:@"sound-file" ofType:@"mp3"];
// If we can access the file...
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
  // Setup the player
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:
     [NSURL fileURLWithPath:path] error:&error];
  // Set the volume (range is 0 to 1)
  player.volume = 0.4f;
  // To minimize lag time before start of output, preload buffers      
  [player prepareToPlay];
  // Play the sound once (set negative to loop)
  [player setNumberOfLoops:0];
  [player play];    
// Cleanup
if (player != nil)
  if (player.isPlaying == YES)
    [player stop];
  [player release];

Comments are closed.