iOS Audio

iOS Audio Recording (AVAudioPlayer & AVAudioRecorder)

View Controller Header File

#import <AVFoundation/AVFoundation.h>

@interface MyViewController : UIViewController
{
@private
	AVAudioPlayer *player;
	AVAudioRecorder *recorder;
}

Start Audio Recording

- (IBAction)startRecord
{
  NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  NSURL *recordURL = [NSURL URLWithString:[cacheDirectory stringByAppendingPathComponent:@"audio.aif"]];

  AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:recordURL settings:nil error:NULL];
  [recorder record];
}

Stop Audio & Play recording

- (IBAction)stopRecord
{
  NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  NSURL *recordURL = [NSURL URLWithString:[cacheDirectory stringByAppendingPathComponent:@"audio.aif"]];

  if (recorder.recording) {
    [recorder stop];
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:recordURL error:NULL];
    [player play];
  }
}

To pause

[player pause];

Control audio volume (0 to 1)

player.volume=0.5;

Forward or rewind

player.currentTime = player.duration * 0.5;

AVPlayer Delegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)sender successfully:(BOOL)success;
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)sender error:(NSError *)error;

Phone call interruption & resume

- (void)audioPlayerBeginInterruption:(AVAudioPlayer*)sender;
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)sender;

Other Audio

System Sound

Register System Sound

SystemSoundID mySound;
NSString *soundFilePath  [[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"caf"];
NSURL *soundFileURL = [NSURL URLForString:soundFilePath];
AudioServicesCreateSystemSoundID((CFURLRef)soundFileURL, &mySound);

Playing System Sound

AudioServicesPlaySystemSound(mySound);

Free the Sound

AudioServicesDisposeSystemSound(mySound);

Vibrate

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

iPod Audio Library

  • MPMediaPickerController to pick the Audio
  • MPMusicPlayerController to play the Audio