Saturday, May 9, 2009

To redraw your view

Simply invoke "setNeedsDisplay" or "setNeedsDisplayRect" method in UIView. You never invoke "drawRect" method directly.

- (void)setNeedsDisplay;
- (void)setNeedsDisplayInRect:(CGRect)rect;

Friday, May 8, 2009

When your AvAudioPlayer does not work in Simulator.

When your AvAudioPlayer does not work in Simulator, open directory of "/Library/QuickTime", and remove or move third party add-ons like Perian, DivX etc.

Playing two or more sounds using AVAudioPlayer

For performance, read the sound data into NSData;

NSString* pathOfSound = [[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"caf"];
NSData* dataOfSound = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathOfSound]];


Then, whenever you want to play sound, create a new object of AVAudioPlayer.


AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithData:dataOfSound error:NULL];
player.delegate = self; // for releasing object, see "Playing sound with AVAudioPlayer"
[player play];

Playing sound with AVAudioPlayer

First of all, you need to append "AVFoundation.framework" to your frameworks list.
Groups & Files -> Frameworks -> Add -> Existing Frameworks -> /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.1.sdk/System/Library/Frameworks/AVFoundation.framework


Import avfoundation.h.


#import <avfoundation/avfoundation.h>


Code like this.



NSString *path = [[NSBundle mainBundle] pathForResource:@"MySong" ofType:@"caf"];
AVAudioPlayer* player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self; //for releasing object.
[player play];


To manage memory, you should build delegate method on your controller.

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[player release];
}


To convert .mp3 to .caf or another, use "afconvert" like below.

/usr/bin/afconvert -f caff -d ima4 sound.mp3 sound.caf

Formatted String

To build formatted string like "printf" in C.

NSString* formattedString = [NSString stringWithFormat:@"NSString:%@, int:%d, float:%f", @"string", 1, 0.1];