iOS: Small refactor to centralize audio session mode management

This commit is contained in:
Henrik Rydgård 2024-05-27 14:50:04 +02:00
parent 79c3762938
commit 07b6938de1
3 changed files with 28 additions and 6 deletions

View File

@ -64,6 +64,9 @@
[self setOriginalFrame: [gameWindow frame]];
[self setOriginalBounds:[gameWindow bounds]];
[self setOriginalTransform:[gameWindow transform]];
// TODO: From iOS 13, should use UIScreenDidConnectNotification instead of the below.
// Display connected
[[NSNotificationCenter defaultCenter] addObserverForName:UIScreenDidConnectNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull notification) {
UIScreen *screen = (UIScreen *) notification.object;
@ -74,8 +77,7 @@
return;
}
// Ignore mute switch when connected to external display
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
iOSCoreAudioSetDisplayConnected(true);
[self updateScreen:screen];
}];
// Display disconnected
@ -89,8 +91,7 @@
UIScreen *newScreen = [[self extDisplays] lastObject];
[self updateScreen:newScreen];
} else {
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
iOSCoreAudioSetDisplayConnected(false);
[self updateScreen:[UIScreen mainScreen]];
}
}];

View File

@ -19,4 +19,9 @@
// Originally written by jtraynham
void iOSCoreAudioInit();
void iOSCoreAudioShutdown();
void iOSCoreAudioShutdown();
// Ignore mute switch when connected to external display.
// Also, obey other settings.
void iOSCoreAudioUpdateSession();
void iOSCoreAudioSetDisplayConnected(bool connected);

View File

@ -28,6 +28,22 @@
#define SAMPLE_RATE 44100
static AudioComponentInstance audioInstance = nil;
static bool g_displayConnected = false;
void iOSCoreAudioUpdateSession() {
NSError *error = nil;
// Default mode
if (g_displayConnected) {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
} else {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
}
}
void iOSCoreAudioSetDisplayConnected(bool connected) {
g_displayConnected = connected;
iOSCoreAudioUpdateSession();
}
int NativeMix(short *audio, int numSamples, int sampleRate);
@ -75,7 +91,7 @@ void iOSCoreAudioInit()
NSLog(@"%@", error.localizedFailureReason);
}
}
if (audioInstance) {
// Already running
return;