Thursday 13 December 2012

How to Override Silent switch while playing sounds in an iPhone/iPad app using AVPlayer

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.

You can follow How to play sounds in an iPhone/iPad app tutorial to learn how to play sounds in an iOS app.

The trick to override the switch is possible only by using AVPlayer, and here is how we can accomplish that.
Just use the below line, must be used in viewDidLoad or some where before using AVPlayer classes.

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

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.

Links Section

Hello developers, 

In the journey so far even i stuck up at some moments from days to weeks. Later on searching several forums and tutorials got solution to get through the difficulties easily. So in this section i will share the links of the blogs, forum's Q&A, tutorials which really helped me really a lot to fix my issues or get it done. 
And also some interesting links which i found.

HTMLParsing, as the name says i got a task to parse html content with in xml response to extract the content within. After some few search straight forward i got a tutorial which explained the steps beautifully, you all know the source of the tutorial, yes you are right its from Raywenderlich.                    

Orientations in iOS 6, as you all know apple changed its apis relate to orientations. I tried many options with the available new api's but none of them lead to success, finally got this tutorial from Shabbir's Forum, then everything worked like charm.

 GeoNames, The geographical database covers all countries and contains over eight million place names that are available for download free of charge. This provides the data in many formats so for newbie it will great site to learn parsing data from server, and more over it also has data in other formats too. Have a look at the GeoNamesWebServices Overview.

Creating Static Libraries For iOS, you might have seen some libraries in xcode such as "libxml2.2", and many more. These are static libraries, this tutorial helps you to create your own static libraries.

Simple XML to NSDictionary Converter, as the name indicates its a simple XML to dictionary converter.

Generate PDF programmatically in iPhone/iPad SDK, generating your own pdf through code.

Saving Layers, slice the images from any Photoshop file. Extract layers as png files and implement in your app.

CoreData Basics Part 7 – Search Bars, many of you have wondered how search display controller is help ful, this tutorial is about that. Apart from that it integrates with the your core data too using fetch controller.

 Icons Pedia, a free site to get png files artworks for your app. And also you can create the app using these free artworks as a prototype app and later you can show it to your designer to create the artworks for your own.

 ZooZ- In-App Payments, apple has its own in-app purchase, which does the payments from the users app store accounts as it is linked with users Credit Card info. Apple says the app must use apple's in-app purchase if it deals with digital content. If you are selling a physical goods, you may opt user directly pays you through his Debit/Credit card, Zooz is one such payment gate way enables the user to pay through Debit/Credit card from your app. It also has an option to pay through PayPal.

 Upload your App - Diawi - Development iOS Apps Wireless Installation, this enables to download the app directly to your device through device's browser. You can upload the build to this site and send the link to your client so that he can download the app directly to his device and start testing.

Base64Online - base64 decode and encode, encoding & decoding any image in base64 format, which is a string of characters. You can send this data to your server from device to upload image files. This link provides to encode & decode images into base64 formats online.


Happy Coding,
Vishy