首页 文章

何时以及如何正确停用音频会话?

提问于
浏览
4

AVFoundation让我有点失落,你是我最后的希望!

我正在写一个锻炼应用程序,我有时会播放简短的提示,例如:“你踩10分钟”或“好!”

Apple建议在播放提示之前激活音频会话,并在播放提示后始终将其停用 . 不仅仅是推荐这是我想要的,因为我使用选项:AVAudioSessionCategoryOptionDuckOthers,我只是想在提示播放时躲避音乐播放器,而不是之前,而不是之后 .

我不知道如何实现这一目标!因为我不太确定停用音频会话的方法,我的第一个想法是使用“while” .

这是我的AudioController类:

#import "AudioController.h"

@interface AudioController ()


@property(strong,nonatomic)AVAudioPlayer *audioPlayerGood;

@end


@implementation AudioController

-(id)init
{
    self=[super init];
    if (self) {
        [self configureAudioSession];
        [self preparePlayers];
    }
    return self;
}

-(void)configureAudioSession
{
    self.audioSession = [AVAudioSession sharedInstance];
    NSError *setCategoryError = nil;
    [self.audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:&setCategoryError];

}


-(void)preparePlayers
{
    NSError *initAudioPlayerError = nil;

    NSURL *urlGood = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Correct" ofType:@"caf"]];



    self.audioPlayerGood = [[AVAudioPlayer alloc] initWithContentsOfURL:urlGood error:&initAudioPlayerError];

   if (initAudioPlayerError) {
        NSLog(@"Error in audioPlayer: %@",[initAudioPlayerError localizedDescription]);
    }


    [self.audioPlayerGood prepareToPlay];
 }

-(void)playCorrect
{
    NSError *activationError = nil;
    [self.audioSession setActive:YES error:&activationError];
    [self.audioPlayerGood play];
    NSLog(@"****************Correct played***************");
    while (self.audioPlayerGood.playing) {
        break;
    }
    [self.audioSession setActive:NO error:&activationError];
 }


@end

然后我在其他类中使用playCorrect方法初始化一个AudioController对象:

[self.audioController playCorrect];

但是在播放声音之后,调试区域会打印出这个文本:

AVAudioSession.mm:646: - [AVAudioSession setActive:withOptions:error:]:停用已运行I / O的音频会话 . 在停用音频会话之前,应停止或暂停所有I / O.

如果十秒后我想再次播放这个声音它将无法正常工作,而方法playCorrect应该重新激活音频会话...所以我不知道什么是停用音频会话的正确方法,什么时候这样做,如果有人可以帮我这个:)

2 回答

  • -1

    什么是while循环应该做什么?

    你最好听完播放器播放完毕,然后停用会话 .

    [NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(finishedPlaying:) 
        name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
    
  • 0

    当解雇 ViewController 时,你必须暂停/释放 audioSession . 有 pause 方法 audioSession

相关问题