簡體   English   中英

使用AVAudioSession暫停和播放音頻

[英]Pause and play audio with AVAudioSession

我有1個控制器。 首先,我開始播放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];
}

但是,當我隱藏我的應用程序音頻時,聲音不會暫停。 我想在我隱藏我的應用程序時暫停音頻,並在應用程序進入前台時在暫停點播放。 怎么做?

為此,您需要為應用程序添加通知,在后台和前台輸入。

首先聲明玩家

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

添加“輸入背景”方法。

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

添加Enter前景方法。

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

您可以使用通知來檢測應用程序將進入背景/前景。

[[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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM