【问题标题】:AVAudioPlayer UIButton - second touch stop current audio playAVAudioPlayer UIButton - 第二次触摸停止当前音频播放
【发布时间】:2011-03-09 14:09:12
【问题描述】:

我有一个 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];
            }
}

【问题讨论】:

    标签: iphone ipad avaudioplayer


    【解决方案1】:

    嗯,我就是这样做的,它只播放一次:

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

    我可能还应该在初始化 audioPlayer 之前检查 nil,所以它只完成了一次......但现在 - 它可以工作。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      -(IBAction) buttonNoisePlay {
      
          if(sound == nil || sound.playing == NO)  //if not playing
          {
              ...
              //if nil initialize
      
              [sound play];
          }
          else
          {
              [sound stop];
          }
      }
      

      【讨论】:

      • 谢谢。我编辑了代码,但结果仍然相同。连续触摸两次按钮会播放音频文件两次而不是停止它。我需要在头文件中定义“播放”吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多