Thursday 13 December 2012

How to play sounds in an iPhone/iPad app And Override Silent switch

As you guys know there are 2 ways to play sound files from the within app like game sounds, warning/caution sounds or alarm sounds.

One is by using Audio Services in AudioToolBox frame work.
And the other is by using AVPlayer in AVFoundation frame work.

Using AudioToolBox

In your header file, just import the class "AudioToolbox/AudioToolbox.h"
and declare a variable for the soundId, used to identify the sound and played at any instance.

SystemSoundID _soundId;


In your implementation file write the below method to create the soundId for the required sound file, usually call this method from viewDidLoad.


- (void) createSoundId
{
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"light_chime" ofType:@"mp3"];
if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath])
{
NSURL* soundPathURL = [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID((CFURLRef)soundPathURL, &_soundId);
}
}


And then its done, you can play for the created soundId as many times as you can using below code.

AudioServicesPlaySystemSound(_soundId);


Once the work is done, you need to disconnect or discard this soundId by using below line, you can also use it to stop playing the sound at any time while playing.

AudioServicesDisposeSystemSoundID(_soundId);


And remember once the soundId is disposed you need to create the soundId again in order to play the same sound again.

Using AVPlayer

There is one limitation using AudioToolBox, it plays sounds which have less then 30seconds duration. For sounds more than 30seconds duration, AVPlayer is the choice.

In your header file, just import the class "AVFoundation/AVFoundation.h"
And just use the below lines to play any sound using AVPlayer

NSString *soundPath = ResourcePath(kSoundName);
NSURL *soundFileURL = [NSURL fileURLWithPath:soundPath];
NSError* error1 ;
AVAudioPlayer * audioPalyer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: &error1];
if (nil == audioPalyer)
{
NSLog(@"Failed to play %@, %@", soundFileURL, error1);
return;
}
[audioPalyer prepareToPlay];
[audioPalyer setVolume:3];
[audioPalyer setDelegate:nil];
audioPalyer.numberOfLoops = 1;
[audioPalyer play];


And to override the silent switch just use the below line, must be used in viewDidLoad or some where before using AVPlayer classes.

[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: nil];


Download the working sample code here.

Happy coding.

1 comment: