Apple did not post any alternative code for this on the Apple Developer site.
Swift version:
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch let error {
print("\(error.localizedDescription)")
}
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .spokenAudio)
} catch let error {
print("\(error.localizedDescription)")
}
1. for this code
AudioSessionInitialize( NULL, NULL, interruptionCallback, self );
replace with
[[AVAudioSession sharedInstance] setActive:YES error:nil];
2. fro this code
UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
AudioSessionSetProperty(
kAudioSessionProperty_AudioCategory,
sizeof(sessionCategory),
&sessionCategory
);
replace with
UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
[[AVAudioSession sharedInstance]
setCategory:sessionCategory error:nil];
You should use AVAudioSession.
To replace the functionality provided by deprecated AudioSessionInitialize (e.g. if you need to specify AudioSessionInterruptionListener callback) you can subscribe for AVAudioSessionInterruptionNotification notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionDidChangeInterruptionType:)
name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
And implement your audioSessionDidChangeInterruptionType: handler like:
- (void)audioSessionDidChangeInterruptionType:(NSNotification *)notification
{
AVAudioSessionInterruptionType interruptionType = [[[notification userInfo]
objectForKey:AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
if (AVAudioSessionInterruptionTypeBegan == interruptionType)
{
}
else if (AVAudioSessionInterruptionTypeEnded == interruptionType)
{
}
}
The equivalent code to
// C way
UInt32 category = kAudioSessionCategory_MediaPlayback ;
OSStatus result = AudioSessionSetProperty(
kAudioSessionProperty_AudioCategory, sizeof(category), &category ) ;
if( result ) // handle the error
Is
// Objective-C way
NSError *nsError;
[[AVAudioSession sharedInstance]
setCategory:AVAudioSessionCategoryPlayback error:&nsError];
if( nsError != nil ) // handle the error
In swift we can add the following
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(true)
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
} catch {
print("Setting category to AVAudioSessionCategoryPlayback failed.")
}
from: https://developer.apple.com/documentation/avfoundation/avaudiosession