CodexBloom - Programming Q&A Platform

implementing AVAudioPlayer not playing audio after interrupting and resuming on iOS 15

👀 Views: 30 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-02
AVFoundation AVAudioPlayer iOS audio-session Objective-C

I'm collaborating on a project where I've been banging my head against this for hours... I'm experiencing an scenario with `AVAudioPlayer` in my Objective-C application where audio playback does not resume properly after being interrupted by a phone call on iOS 15. I've implemented the audio session configuration, but after the interruption, the audio player seems to be in a stopped state even though I attempt to call `play` on it again. Here is the relevant part of my implementation: ```objective-c #import <AVFoundation/AVFoundation.h> @interface MyAudioPlayer : NSObject @property (strong, nonatomic) AVAudioPlayer *audioPlayer; @end @implementation MyAudioPlayer - (void)setupAudioSession { AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *setCategoryError = nil; [audioSession setCategory:AVAudioSessionCategoryPlayback behavior:&setCategoryError]; if (setCategoryError) { NSLog(@"behavior setting category: %@", setCategoryError); } NSError *activeError = nil; [audioSession setActive:YES behavior:&activeError]; if (activeError) { NSLog(@"behavior activating session: %@", activeError); } } - (void)playAudio { NSURL *audioURL = [[NSBundle mainBundle] URLForResource:@"myAudioFile" withExtension:@"mp3"]; self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL behavior:nil]; [self.audioPlayer play]; } - (void)audioSessionInterrupted:(NSNotification *)notification { NSDictionary *info = notification.userInfo; if ([info[AVAudioSessionInterruptionTypeKey] intValue] == AVAudioSessionInterruptionTypeBegan) { [self.audioPlayer pause]; } else if ([info[AVAudioSessionInterruptionTypeKey] intValue] == AVAudioSessionInterruptionTypeEnded) { [self.audioPlayer play]; // This doesn't work as expected } } @end ``` I've registered for audio session interruption notifications like this: ```objective-c [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionInterrupted:) name:AVAudioSessionInterruptionNotification object:nil]; ``` However, when the interruption ends, `self.audioPlayer.play` does not seem to resume playback. Also, I've tried checking the `self.audioPlayer.isPlaying` property, and it returns NO despite the call to play. I suspect this might be due to the audio session not being set up correctly after the interruption. Is there anything I'm missing in terms of handling the audio session state or resetting the audio player? Any insights or best practices would be greatly appreciated! I'm working on a CLI tool that needs to handle this. What's the best practice here? Any ideas what could be causing this? Thanks for taking the time to read this!