2011-03-09 345 views
0

我有一个UIButton,当触摸时播放音频文件。此刻连续两次触摸该按钮可以播放音频文件两次而不是停止播放。AVAudioPlayer UIButton - 第二次触摸停止当前音频播放

我期待有第二次点击停止音频文件,而不是播放第二个实例。任何建议将非常感激。感谢

-(IBAction) buttonNoisePlay { 

     NSString *pathsoundFile = [[NSBundle mainBundle] pathForResource:@"noise" ofType:@"mp4"]; 
     sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathsoundFile] error:NULL]; 
     sound.delegate = self; 
     sound.numberOfLoops = -1; 
     sound.volume = 1; 

      if(sound == nil || sound.playing == NO) //if not playing 
      { 

        [sound play]; 
      } 
      else 
      { 
        [sound stop]; 
      } 
} 

回答

1

你可以做这样的事情:

-(IBAction) buttonNoisePlay { 

    if(sound == nil || sound.playing == NO) //if not playing 
    { 
     ... 
     //if nil initialize 

     [sound play]; 
    } 
    else 
    { 
     [sound stop]; 
    } 
} 
+0

谢谢。我编辑了代码,但仍然是相同的结果。连续触摸按钮两次,而不是停止播放音频文件两次。我需要在头文件中定义“正在播放”吗? – hanumanDev 2011-03-09 20:30:13

2

嗯,这是我做&只播放一次:

-(void) playSound: (NSString *) strFileName 
{  
    if(audioPlayer == nil || audioPlayer.playing == NO) //check if it's already playing in case they dbl-tapped (or more) b/c we only want to play it once per found item 
    { 
     //Get the filename of the sound file: 
     NSString *urlAddress = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], strFileName]; 

     //Get a URL for the sound file 
     NSURL *url = [NSURL fileURLWithPath:urlAddress]; 
     NSError *error; 

     //Use AVAudioPlayer to play the sound 
     audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
     audioPlayer.numberOfLoops = 0; 

     if (audioPlayer == nil) 
      NSLog(@"audioPlayer nil Error:%@", [error description]); 
     else 
      [audioPlayer play]; 
    } 
} 

而且在标题:

AVAudioPlayer *audioPlayer; 

I在初始化audioPlayer之前,应该也可以检查零,所以它只能做一次......但现在 - 它的工作。