I am using AVAudioPlayer
and NSFileHandle
to do audio streaming. The basic idea is that I save the streaming audio data to the device with file system and then use AVAudioPlayer
to playback the file just saved. AVAudioPlayer
can still play that file even the streaming is in progress.
I have a UIButton
to start streaming/downloading. When the downloaded data is accumulated to a specific amount of Bytes, AVAudioPlayer
will play (the "play" method of AVAudioPlayer
is triggered) automatically. My question is: I tap the button to start streaming/downloading, then press iPhone's home button very soon to make my app go to background. The download keeps working in the background but the "play" method of AVAudioPlayer
returns "NO" which means the "play" method doesn't play the audio.
I added AVAudioSession
related code to my audio player's init method:
- (id) initWithURL:(NSString *) downloadedMusicURL
{
if ((self = [super init]))
{
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
CFURLRef url = CFURLCreateWithFileSystemPath (NULL, (CFStringRef)downloadedMusicURL, kCFURLPOSIXPathStyle, FALSE);
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:CFBridgingRelease(url) error:nil];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
}
return self;
}
Also in the info.plist I added an item "App plays audio" for the Key "Required background modes". However, the "play" still doesn't get called properly in the background. What else did I miss? Thanks a lot in advance.