首页 文章

除非单击 playing(selected)按钮,否则触发 AVAudioPlayer 以停止所有声音和播放

提问于
浏览
2

我正在创建一个声音板应用程序,一次播放一个声音。我希望 UIButton 能够阻止所有其他声音播放,并在点击时开始播放自己的声音。我有一个 AVAudioPlayer 设置播放所有声音(我点击时更改声音文件网址,因为我一次只想要一个声音播放这不是一个问题)。我想知道如何根据按下的按钮停止所有其他声音并播放声音,但如果单击的按钮是当前正在播放声音的按钮,则该按钮仅停止声音。我知道这可以通过分离音频播放器和触发停止事件来实现,但我想避免复制和粘贴代码并尽可能保持高效,而且我只想要/需要一个音频层。这是我的代码:

- (IBAction)play {
 if (audioPlayer.playing == NO) {
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/k.mp3", [[NSBundle mainBundle] resourcePath]]];
    NSError *error;
     [audioPlayer release];
     audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;

    AVAudioSession *audiosession = [AVAudioSession sharedInstance];
    [audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];

    [audioPlayer play];
    [start setTitle:@"Stop" forState:UIControlStateNormal];
}
 else
     if (audioPlayer.playing == YES) {
         [audioPlayer stop];
     [start setTitle:@"Start" forState:UIControlStateNormal];
    }
    }

- (IBAction)play2 {
if (audioPlayer.playing == NO) {
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/chicken.mp3", [[NSBundle mainBundle] resourcePath]]];
    NSError *error;
    [audioPlayer release];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;

    AVAudioSession *audiosession = [AVAudioSession sharedInstance];
    [audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];

    [audioPlayer play];
    [start2 setTitle:@"Stop" forState:UIControlStateNormal];
} else
    if (audioPlayer.playing == YES) {
        [audioPlayer stop];
        [start2 setTitle:@"Start" forState:UIControlStateNormal];
    }
}

任何帮助表示赞赏。先感谢您!

2 回答

  • 3

    就这样做吧

    -(void)stopAudio{
    
    if(audioPlayer && [audioPlayer isPlaying]){
        [audioPlayer stop];
        audioPlayer=nil;
    }
    
    }
    

    并在每次点击时调用此功能..

    - (IBAction)play2 {
        [self stopAudio];
    
        //Do your Stuffs
    }
    
  • 0

    单击按钮时,停止播放音频播放器并分配新的歌曲 URL,然后在单击按钮播放歌曲时播放 it.Write 此代码。

    if(audioPlayer.isPlaying)
          [audioPlayer stop];    
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSURL *url = [NSURL fileURLWithPath:YourSoundURL];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.delegate=self;
    [audioPlayer play];
    [start2 setTitle:@"Stop" forState:UIControlStateNormal];
    

相关问题