Je joue de la musique en utilisant AVAudioPlayer en arrière-plan. Le problème est le suivant: s'il y a un appel entrant qui interrompt le lecteur, il ne reprendra jamais sauf s'il passe au premier plan et le fait manuellement.
Le code est simple, pour le jouer en arrière-plan:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error: nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil]; url = [[NSURL alloc] initFileURLWithPath:...]; audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL: url error:NULL]; audio_player.delegate = self; bool ret = [audio_player play];
déléguer pour gérer les interruptions:
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player { //sortinged this, not working [[AVAudioSession sharedInstance] setActive: NO error: nil]; NSLog(@"-- interrupted --"); } //----------- THIS PART NOT WORKING WHEN RUNNING IN BACKGROUND ---------- - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player { NSLog(@"resume!"); //--- sortinged, not working: [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error: nil]; //--- sortinged, not working: [[AVAudioSession sharedInstance] setActive: YES error: nil]; //--- sortinged, not working: [audio_player prepareToPlay]; [audio_player play]; }
Quelqu'un peut-il m'aider?
Trouvé la solution! J'ai eu le même problème, mon application reprenait joliment l'audio après une interruption, seulement si mon application était ouverte. Quand il était sur le fond, il a échoué à reprendre la lecture de l'audio après une interruption.
J'ai corrigé ceci en ajoutant les lignes de code suivantes:
Ajoutez cette ligne chaque fois que votre application commence à lire de l'audio. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Et sur la méthode endInterruption, attendez 1 ou 2 secondes avant de reprendre la lecture de l'audio. Cela permet au operating system d'arrêter d'utiliser le canal audio.
- (void)endInterruptionWithFlags:(NSUInteger)flags { // Validate if there are flags available. if (flags) { // Validate if the audio session is active and immediately ready to be used. if (AVAudioSessionInterruptionFlags_ShouldResume) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{ // Resume playing the audio. }); } } }
Vous pouvez également append cette ligne lorsque votre application s'arrête (pas en pause) en jouant de l'audio. Mais n'est pas requirejs. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Essaye ça
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)audioPlayer withFlags:(NSUInteger)flags{ if (flags == AVAudioSessionFlags_ResumePlay) { [audioPlayer play]; }
J'espère que cela aide.