2017-10-04 8 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

가능한 복제 [PLAY/동일한 버튼 \ 일시 정지와 [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