Playing audio in iOS using AVAudioPlayer

Playing audio in an iOS app consists of two steps:

  1. Creating an Audio session using AVAudioSession class.
  2. Playing the audio using Audio player using AVAudioPlayer class.

AVAudioSession

We want to play audio in apps even though the background music is running. For that, create a shared audio session. The code for initializing a shared session is shown below.

-(void)initAudio
{
    NSError *error;
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
    BOOL success = [[AVAudioSession sharedInstance] setActive: YES error: &error];
    if(!success)
        NSLog(@"The audio session activation error is %@" , error.description);
    else
        NSLog(@"The audio session is activated");
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self initAudio];
    return YES;
}

We use the sharedInstance static method to create the session. And set the category to Ambient. Ambient category suggests that app can function without audio. Further, audio from other apps mixes with your audio.

Create the session when the app starts. Typically, place the code in didFinishLaunchingWithOptions in the AppDelegate class.

AVAudioPlayer

AVAudioPlayer class plays the audio. It needs a delegate (for some reason). Without supplying a AVAudioPlayerDelegate, it throws a error. All methods in the delegate are optional.

-(id)init
{
    self = [super init];
    if(self!=nil)
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"button" ofType:@"mp3" inDirectory:@""];
        NSURL *url = [[NSURL alloc] initFileURLWithPath: path];
        NSError *error;
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error: &error];
        NSLog(@"Error in loading - %@", error.description);
        player.delegate = self;
    }
    return self;
}

-(void)playButtonSound
{
    [player play];
}

Retrieve the path of the mp3 file from the main bundle. Create a NSURL object from the file path. Initialize AVAudioPlayer with the URL. And then, supply a delegate.

The play method of AVAudioPlayer plays the audio.

Related Posts

Leave a Reply

Your email address will not be published.