2010-06-21 130 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){