2017-10-04 160 views
0

我有1個控制器。首先我開始播放audio1。我使用此代碼:暫停並使用AVAudioSession播放音頻

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

但是,當我隱藏我的應用程序音頻沒有暫停。當我隱藏我的應用程序並在應用程序到達前臺時暫停點播放時,我想暫停音頻。怎麼做?

+0

的可能的複製[播放/用相同的按鈕\暫停[AVAudioPlayer \]](https://stackoverflow.com/questions/6635604/play-pause-with-the-same-button-avaudioplayer) – kb920

回答

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]; 
} 
+0

在下一個控制器中,我使用AVAudioSession,並且在此控制器中,如果隱藏應用程序,音頻不應該停止。但是,如果我在下一個控制器中使用您的代碼並隱藏應用程序(當下一個控制器中的音頻播放並且第一個控制器暫停時)並打開第一個控制器的音頻將與第二個控制器的音頻一起播放 – user

0

爲此,您需要爲應用程序在後臺和前臺添加通知。

申報玩家第一

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

添加輸入前臺方法。

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

在下一個控制器中,我使用AVAudioSession,控制器音頻不應該停止如果隱藏應用程序但是,如果我在下一個控制器中使用您的代碼並隱藏應用程序(當下一個控制器中的音頻播放時,第一個控制器中的音頻暫停時),並且從第一個控制器打開音頻將與第二個控制器 – user