2017-10-04 28 views
0

コントローラが1つあります。最初に私はオーディオ1を再生します。私はこのコードを使用します: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

(https://stackoverflow.com/questions/6635604/play-pause-with-the-same-button-avaudioplayer)[再生/同じボタン\ [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を使用していますが、このコントローラーではhide appの場合はオーディオを止めてはいけません。しかし、私はあなたのコードを使用して、次のコントローラ(次のコントローラのオーディオを再生し、最初のコントローラを一時停止した状態)でアプリケーションを隠すと、最初のコントローラのオーディオを2番目のコントローラのオーディオと一緒に再生します。 – 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]; 
} 

追加Enter Foregroundメソッド。

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

次のコントローラではAVAudioSessionを使用し、コントローラのオーディオは、アプリケーションを隠す場合は止めてはいけません。しかし、あなたのコードを使用して、次のコントローラー(次のコントローラーのオーディオを再生し、最初のコントローラーを一時停止したとき)と1番目のコントローラーのオープンオーディオを、2番目のコントローラー – user

関連する問題