2010-06-21 99 views
0

我使用下面的代码播放声音时,用户触摸屏幕上的任何地方,但每当我测试它没有声音播放,也是当我使用相同的代码在一个按钮上播放第二次点击按钮不上第一次点击??触摸事件播放声音?

- (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]; 
     } 
    } 

} 

}

回答

0
AVAudioPlayer *player; // <--- 
if(!player){ 

局部变量是自动初始化为0。一般含量为某个非零垃圾,所以下面if条件将很少满足。

看着你的代码,似乎player将被重新使用。一旦离开函数,局部变量将会丢失。因此,你应该使它成为视图的即时变量(ivar),或者使其成为一个静态变量。

static AVAudioPlayer *player; // <--- 
if(!player){