Friday, June 11, 2010

Audio and Sound

SystemSound API
  • For short sounds only, less than 5 sec
  • for .caf .aif or .wav only
  • No control and immediate playback
      Steps to coding
        1. Register the sound
        2. Play the sound
        3. Optionally can get call back when finished

      Eg:
              NSURL *url = [[NSBundle mainBundle] pathForResource: @"audiofilename" ofType: @"ext"];  
              SystemSoundID id;
              AudioServicesCreateSystemSoundID((CFURLRef)url, &id);
              AudioServicesPlaySystemSound(id);   // to play the sound file

AVAudioPlayer Class
  • High level simple API for playing back long sound (>5sec)
  • Support play, stop, loop, pause, seek
  • Support many more sound formats
     Steps to coding
  • Include the AVFoundation header into the .h file. Eg:
             #import <AVFoundation/AVFoundation.h>

Create AVAudioPlayer from file URL or data, Eg:
             AVAudioPlayer *player;
             NSString *path = [[NSBundle mainBundle] pathForResource: @"audiofilename" ofType: @"ext"];
             NSURL *url = [NSURL fileURLWithPath: path];
             player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error: NULL];

  • Start or stop player as needed. Eg:
             if   (!player.playing) {
                   [player play];
             } else {
                   [player pause];
             }

  • Add AVAudionFoundation Frameworks objects code to the project. Eg:
             In Xcode, under Groups and file Section, Under Frameworks, add ->
            Exsisting Frameworks. Select the AVaudioFoundation.framework to add to the
            Frameworks section.