Wednesday, March 17, 2010

Sound Format Conversion in iPhone

Since iPhone supports only following data formats for audion files:

* linear PCM
* MA4 (IMA/ADPCM)
* µLaw
* aLaw

You may use the afconvert tool to convert sounds. For example, to convert the 16-bit linear PCM system sound Submarine.aiff to IMA4 audio in a CAF file, use the following command in the Terminal application:

afconvert /System/Library/Sounds/Submarine.aiff ~/Desktop/sub.caf -d ima4 -f caff -v

You can inspect a sound to determine its data format by opening it in QuickTime Player and choosing Show Movie Inspector from the Movie menu.

Getting a screenshot of any View Programmatically

Place the code shown here in the main file of your view controller
-(IBAction)captureScreen:(id)sender
{
UIGraphicsBeginImageContext(foobar.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
}

Here foobar is considered the UIView subclass which has the screen to be captured in the screenshot.

Save UIImage Object as a PNG or JPEG File

UIKit includes two C functions, UIImageJPEGRepresentation and UIImagePNGRepresentation which will return an NSData object that represents an image in JPEG or PNG format, respectively. With this information in hand, you can then use the writeToFile method of the NSData object to write the image data to a specified path.

// Create paths to output images
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/TestImage.png"];
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/TestImage.jpg"];

// Write a UIImage to JPEG with minimum compression (best quality)
// The value 'image' must be a UIImage object
// The value '1.0' represents image compression quality as value from 0.0 to 1.0
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];

// Write image to PNG
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];

// Let's check to see if files were successfully written...

// Create file manager
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];

// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

// Write out the contents of home directory to console
NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);


One last note, this application will only run on an actual device as the simulator does not have camera support.

Monday, December 28, 2009

Cookie Management in iPhone

The following code may help people who are looking for some sort of cookie management for their iPhone web application. This post will definitely get you started.

NSURLCredential *userCredentials = [NSURLCredential credentialWithUser:email.text
password:password.text
persistence:NSURLCredentialPersistencePermanent];

NSURLProtectionSpace *space = [[NSURLProtectionSpace alloc] initWithHost:@"localhost"
port:3000
protocol:@"http"
realm:nil
authenticationMethod: NSURLAuthenticationMethodDefault];


[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:userCredentials
forProtectionSpace:space];


After writing the above code, your application will be able to store cookies for the site http://localhost:3000/. You may also change it as per your need and requirement, such as:

* May use three different types of persistence storage for cookies: NSURLCredentialPersistenceNone,
NSURLCredentialPersistenceForSession,
NSURLCredentialPersistencePermanent

* May use different authentications. AuthenticationMethod should be set to one of the values in NSString *NSURLProtectionSpaceHTTPProxy;
NSString *NSURLProtectionSpaceHTTPSProxy;
NSString *NSURLProtectionSpaceFTPProxy;
NSString *NSURLProtectionSpaceSOCKSProxy;

or nil to use the default, NSURLAuthenticationMethodDefault.

For more information, refer to Apple's documentation.

Tuesday, December 15, 2009

Sound Playback in iPhone

Today I am going to post two ways to play sounds in iPhone.

1st Approach: Using Audio Toolbox
NSString *sound = [NSString stringWithFormat:@"sound"];
NSString *path = [[NSBundle mainBundle] pathForResource:sound ofType:@"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound(soundID);


Of course, for this to work you need to add the AudioToolbox foundation to your project. Also it doesn't like the compressed audio of mp3's, etc. It is more suited for wav's.

2nd Approach: Using AVAudioPlayer class
The AVAudioPlayer class makes it very easy to play mp3s as well.
-(IBAction)playSound:(id)sender{

NSString *newAudioFile = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"mp3"];

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile] error:NULL];

[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
BOOL plays = [audioPlayer play];

}


For this to work, you need to add the AVFoundation to your project:
Project -> Add ->
Developer:Platforms:iPhoneSimulator.platform:Developer:SDKs:iPhoneSiumulator2.2.sdk:System:Library:Frameworks:AVFoundation.framework

Make sure to NOT copy it into your project when you are given the dialog box.

AVAudioPlayer provides a really straightforward interface, but it might not be appropriate for playing really short sounds that are synchronized with your app. AudioServices is really intended to play short sounds, and it works very well for that.

Adding the following line to your code, before you start the player, should cause the audioPlayer to loop indefinitely, until you issue a stop message:
[audioPlayer setNumberOfLoops:-1];

after the setDelegate function call.

Note that, with MP3, you may run into issues if you need to play multiple sounds at the same time:

Coding How-Tos: Audio and Video
The following limitations pertain for simultaneous sounds in iPhone OS, depending on the audio data format:

* AAC, MP3, and ALAC (Apple Lossless) audio: no simultaneous playback; one sound at a time.