i am using the following code to play a sound when user touches anywhere at the screen but whenever i test it no sound is played and also when i use the same code on a button it plays on the second click on the button not on the first click??
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self.view];
if (CGRectContainsPoint(CGRectMake(320,480,0,0),point));//CGRectMake(5, 5, 40, 130), point))
{
AVAudioPlayer *player;
if(!player){
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:@"/try.wav"];
NSLog(@"Path to play: %@", resourcePath);
NSError* err;
//Initialize our player pointing to the path to our resource
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
if( err ){
//bail!
NSLog(@"Failed with reason: %@", [err localizedDescription]);
}
else{
//set our delegate and begin playback
player.delegate = self;
[player play];
}
}
}
}
Local variables are not automatically initialized to 0. Usually the content is some non-zero garbage, so the following
ifcondition will seldom satisfy.Looking at your code it seems that the
playerwill be reused. Local variables will be lost once leaving the function. Therefore, you should make it an instant variable (ivar) of the view, or make it a static variable.