使用AVAudioSession暂停和播放音频

时间:2017-10-04 07:03:55

标签: ios objective-c avaudiosession

我有一个控制器。首先我开始播放audio1。我使用这段代码:

- (void)viewDidLoad
{

     //code to not turn off audio with using mute switch

     [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
     [[AVAudioSession sharedInstance] setActive: NO error: nil];

      //code to play audio

      NSString *soundFilePath = [NSString stringWithFormat:@"%@/%@.mp3",[[NSBundle mainBundle] resourcePath], @"sound"];
      NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
      _player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
      _player.numberOfLoops = -1;
      [_player play];
}

但是当我隐藏我的应用时,音频没有暂停。当我隐藏我的应用程序时,我想暂停音频,当应用程序到达前台时,我想在暂停点播放。怎么做?

2 个答案:

答案 0 :(得分:2)

为此,您需要为后台和前景中的应用输入添加通知。

首先声明玩家

 AVAudioPlayer *player;

在ViewDidLoad中添加此代码

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackgroundActive:) name:UIApplicationDidEnterBackgroundNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForegroundActive:) name:UIApplicationWillEnterForegroundNotification object:nil];

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

[[AVAudioSession sharedInstance] setActive: NO error: nil];

//code to play audio
NSString *soundFilePath = [NSString stringWithFormat:@"%@/%@.mp3",[[NSBundle mainBundle] resourcePath], @"alarm_tone"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1;
[player play];

添加Enter背景方法。

-(void)appEnterBackgroundActive:(NSNotification*)note
{
     [player pause];
}

添加输入前景方法。

-(void)appEnterForegroundActive:(NSNotification*)note
{
    [player play];
}

答案 1 :(得分:0)

你可以使用通知检测应用程序将进入后台/前台。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground:) name:@"enterBackGroundNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForeground:) name:@"enterForeGroundNotification" object:nil];

- (void)appEnterBackground:(NSNotification *) notification {
   [_player pause];
}

- (void)appEnterForeground:(NSNotification *) notification {
   [_player play];
}