Issue with playing music file during a phone calli

2019-09-17 11:35发布

问题:

I have two pieces of code:

Code 1 - This is playing a music file via the in-ear speaker:

NSString *tileDirectory = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"8Ocean.mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:tileDirectory];
NSError *error=nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if(!error)
{
    [self.audioPlayer prepareToPlay];
    UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
    [self.audioPlayer play];
}
else
{
    NSLog(@"%@",error.localizedDescription);
}

Code 2- This is playing a music file during a phone call (is routed to in-ear or speaker phone depending on user setting during the phone call)

NSString *tileDirectory = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"8Ocean.mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:tileDirectory];
NSError *error=nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if(!error)
{
    [self.audioPlayer prepareToPlay];
    self.audioPlayer.volume=10.0;
    UInt32 sessionCategory = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
    [self.audioPlayer play];
}
else
{
    NSLog(@"%@",error.localizedDescription);
}

My issue is:

Code 1 and 2 work well independently. However, after using code 1, code 2 will not work at all (unless the app is killed and restarted)

I have tried everything I can think of but cannot work out where the problem is from.

回答1:

Your app needs to handle audio session interruptions from phone calls in order for audio processing not to be killed for your app.