Compare commits

..

2 Commits

Author SHA1 Message Date
Toni Förster
4855f9bead fix tvOS build
Signed-off-by: Toni Förster <toni.foerster@gmail.com>
2024-09-13 11:48:40 +02:00
Toni Förster
a65ed67751 proper audio interrupt and route change handling
- set AVAudioSession inactive on pause and stop
- handle audio route changes
2024-09-13 11:21:07 +02:00
7 changed files with 175 additions and 56 deletions

View File

@@ -181,7 +181,9 @@ final class AVPlayerBackend: PlayerBackend {
{ {
seek(to: 0, seekType: .loopRestart) seek(to: 0, seekType: .loopRestart)
} }
#if !os(macOS)
model.setAudioSessionActive(true)
#endif
avPlayer.play() avPlayer.play()
// Setting hasStarted to true the first time player started // Setting hasStarted to true the first time player started
@@ -196,7 +198,9 @@ final class AVPlayerBackend: PlayerBackend {
guard avPlayer.timeControlStatus != .paused else { guard avPlayer.timeControlStatus != .paused else {
return return
} }
#if !os(macOS)
model.setAudioSessionActive(false)
#endif
avPlayer.pause() avPlayer.pause()
model.objectWillChange.send() model.objectWillChange.send()
} }
@@ -210,6 +214,9 @@ final class AVPlayerBackend: PlayerBackend {
} }
func stop() { func stop() {
#if !os(macOS)
model.setAudioSessionActive(false)
#endif
avPlayer.replaceCurrentItem(with: nil) avPlayer.replaceCurrentItem(with: nil)
hasStarted = false hasStarted = false
} }
@@ -364,11 +371,7 @@ final class AVPlayerBackend: PlayerBackend {
let startPlaying = { let startPlaying = {
#if !os(macOS) #if !os(macOS)
do { self.model.setAudioSessionActive(true)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
self.logger.error("Error setting up audio session: \(error)")
}
#endif #endif
self.setRate(self.model.currentRate) self.setRate(self.model.currentRate)

View File

@@ -253,11 +253,7 @@ final class MPVBackend: PlayerBackend {
let startPlaying = { let startPlaying = {
#if !os(macOS) #if !os(macOS)
do { self.model.setAudioSessionActive(true)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
self.logger.error("Error setting up audio session: \(error)")
}
#endif #endif
DispatchQueue.main.async { [weak self] in DispatchQueue.main.async { [weak self] in
@@ -359,6 +355,9 @@ final class MPVBackend: PlayerBackend {
} }
func play() { func play() {
#if !os(macOS)
model.setAudioSessionActive(true)
#endif
startClientUpdates() startClientUpdates()
startRefreshRateUpdates() startRefreshRateUpdates()
@@ -387,6 +386,9 @@ final class MPVBackend: PlayerBackend {
} }
func pause() { func pause() {
#if !os(macOS)
model.setAudioSessionActive(false)
#endif
stopClientUpdates() stopClientUpdates()
stopRefreshRateUpdates() stopRefreshRateUpdates()
@@ -408,6 +410,9 @@ final class MPVBackend: PlayerBackend {
} }
func stop() { func stop() {
#if !os(macOS)
model.setAudioSessionActive(false)
#endif
stopClientUpdates() stopClientUpdates()
stopRefreshRateUpdates() stopRefreshRateUpdates()
client?.stop() client?.stop()

View File

@@ -232,6 +232,14 @@ final class PlayerModel: ObservableObject {
name: AVAudioSession.interruptionNotification, name: AVAudioSession.interruptionNotification,
object: nil object: nil
) )
// Register for audio session route change notifications
NotificationCenter.default.addObserver(
self,
selector: #selector(handleRouteChange(_:)),
name: AVAudioSession.routeChangeNotification,
object: AVAudioSession.sharedInstance()
)
#endif #endif
playbackMode = Defaults[.playbackMode] playbackMode = Defaults[.playbackMode]
@@ -250,7 +258,15 @@ final class PlayerModel: ObservableObject {
#if !os(macOS) #if !os(macOS)
deinit { deinit {
NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil) NotificationCenter.default.removeObserver(
self, name: AVAudioSession.interruptionNotification, object: nil
)
NotificationCenter.default.removeObserver(
self,
name: AVAudioSession.routeChangeNotification,
object: AVAudioSession.sharedInstance()
)
} }
#endif #endif
@@ -1276,12 +1292,27 @@ final class PlayerModel: ObservableObject {
} }
#if !os(macOS) #if !os(macOS)
func setAudioSessionActive(_ setActive: Bool) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
do {
try AVAudioSession.sharedInstance().setActive(setActive)
} catch {
self.logger.error("Error setting up audio session: \(error)")
}
}
}
@objc func handleAudioSessionInterruption(_ notification: Notification) { @objc func handleAudioSessionInterruption(_ notification: Notification) {
logger.info("Audio session interruption received.") logger.info("Audio session interruption received.")
logger.info("Notification received: \(notification)") logger.info("Notification object: \(String(describing: notification.object))")
guard let info = notification.userInfo, guard let info = notification.userInfo else {
let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt, logger.info("userInfo is missing in the notification.")
return
}
// Extract the interruption type
guard let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: typeValue) let type = AVAudioSession.InterruptionType(rawValue: typeValue)
else { else {
logger.info("AVAudioSessionInterruptionTypeKey is missing or not a UInt in userInfo.") logger.info("AVAudioSessionInterruptionTypeKey is missing or not a UInt in userInfo.")
@@ -1290,23 +1321,103 @@ final class PlayerModel: ObservableObject {
logger.info("Interruption type received: \(type)") logger.info("Interruption type received: \(type)")
// Check availability for iOS 14.5 or newer to handle interruption reason
// Currently only for debugging purpose
#if os(iOS)
if #available(iOS 14.5, *) {
// Extract the interruption reason, if available
if let reasonValue = info[AVAudioSessionInterruptionReasonKey] as? UInt,
let reason = AVAudioSession.InterruptionReason(rawValue: reasonValue)
{
logger.info("Interruption reason received: \(reason)")
switch reason {
case .default:
logger.info("Interruption reason: Default or unspecified interruption occurred.")
case .appWasSuspended:
logger.info("Interruption reason: The app was suspended during the interruption.")
@unknown default:
logger.info("Unknown interruption reason received.")
}
} else {
logger.info("AVAudioSessionInterruptionReasonKey is missing or not a UInt in userInfo.")
}
} else {
logger.info("Interruption reason handling is not available on this iOS version.")
}
#endif
// Handle the specific interruption type
switch type { switch type {
case .began: case .began:
logger.info("Audio session interrupted.")
// We need to call pause() to set all variables correctly, and play()
// directly afterwards, because the .began interrupt is sent after audio
// ducking ended and playback would pause. Audio ducking usually happens
// when using headphones.
pause() pause()
play() logger.info("Audio session interrupted (began).")
case .ended: case .ended:
// Extract any interruption options, if available
if let optionsValue = info[AVAudioSessionInterruptionOptionKey] as? UInt {
logger.info("Interruption options received: \(optionsValue)")
if optionsValue & AVAudioSession.InterruptionOptions.shouldResume.rawValue != 0 {
play()
logger.info("Interruption option indicates playback should resume automatically.")
} else {
logger.info("Interruption option indicates playback should not resume automatically.")
}
} else {
logger.info("AVAudioSessionInterruptionOptionKey is missing or not a UInt in userInfo.")
}
logger.info("Audio session interruption ended.") logger.info("Audio session interruption ended.")
// We need to call pause() to set all variables correctly. // Check if audio was resumed or if there's any indication of ducking
// Otherwise, playback does not resume when the interruption ends. let currentVolume = AVAudioSession.sharedInstance().outputVolume
pause() logger.info("Current output volume: \(currentVolume)")
play()
default: default:
break logger.info("Unknown interruption type received.")
}
}
@objc func handleRouteChange(_ notification: Notification) {
logger.info("Audio route change received.")
guard let info = notification.userInfo else {
logger.info("userInfo is missing in the notification.")
return
}
guard let reasonValue = info[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue)
else {
logger.info("AVAudioSessionRouteChangeReasonKey is missing or not a UInt in userInfo.")
return
}
logger.info("Route change reason received: \(reason)")
let currentCategory = AVAudioSession.sharedInstance().category
logger.info("Current audio session category before change: \(currentCategory)")
switch reason {
case .categoryChange:
logger.info("Audio session category changed.")
let newCategory = AVAudioSession.sharedInstance().category
logger.info("New audio session category: \(newCategory)")
case .oldDeviceUnavailable, .newDeviceAvailable:
logger.info("Audio route change may indicate ducking or device change.")
let currentRoute = AVAudioSession.sharedInstance().currentRoute
logger.info("Current audio route: \(currentRoute)")
for output in currentRoute.outputs {
logger.info("Output port type: \(output.portType), UID: \(output.uid)")
switch output.portType {
case .headphones, .bluetoothA2DP:
logger.info("Detected port type \(output.portType). Executing play().")
play()
default:
logger.info("Detected port type \(output.portType). Executing pause().")
pause()
}
}
case .noSuitableRouteForCategory:
logger.info("No suitable route for the current category.")
default:
logger.info("Unhandled route change reason: \(reason)")
} }
} }
#endif #endif

View File

@@ -15,7 +15,7 @@ struct AppSidebarNavigation: View {
var body: some View { var body: some View {
#if os(iOS) #if os(iOS)
content.introspect(.viewController, on: .iOS(.v15, .v16, .v17, .v18)) { viewController in content.introspect(.viewController, on: .iOS(.v15, .v16, .v17)) { viewController in
// workaround for an empty supplementary view on launch // workaround for an empty supplementary view on launch
// the supplementary view is determined by the default selection inside the // the supplementary view is determined by the default selection inside the
// primary view, but the primary view is not loaded so its selection is not read // primary view, but the primary view is not loaded so its selection is not read

View File

@@ -9,7 +9,7 @@ struct FocusableSearchTextField: View {
var body: some View { var body: some View {
SearchTextField() SearchTextField()
#if os(macOS) #if os(macOS)
.introspect(.textField, on: .macOS(.v12, .v13, .v14, .v15)) { textField in .introspect(.textField, on: .macOS(.v12, .v13, .v14)) { textField in
state.textField = textField state.textField = textField
} }
.onAppear { .onAppear {
@@ -18,7 +18,7 @@ struct FocusableSearchTextField: View {
} }
} }
#elseif os(iOS) #elseif os(iOS)
.introspect(.textField, on: .iOS(.v15, .v16, .v17, .v18)) { textField in .introspect(.textField, on: .iOS(.v15, .v16, .v17)) { textField in
state.textField = textField state.textField = textField
} }
.onChange(of: state.focused) { newValue in .onChange(of: state.focused) { newValue in

View File

@@ -4913,7 +4913,7 @@
repositoryURL = "https://github.com/sindresorhus/Defaults"; repositoryURL = "https://github.com/sindresorhus/Defaults";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 7.3.1; minimumVersion = 7.0.0;
}; };
}; };
372AA40E286D067B0000B1DC /* XCRemoteSwiftPackageReference "Repeat" */ = { 372AA40E286D067B0000B1DC /* XCRemoteSwiftPackageReference "Repeat" */ = {
@@ -4928,8 +4928,8 @@
isa = XCRemoteSwiftPackageReference; isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/hyperoslo/Cache.git"; repositoryURL = "https://github.com/hyperoslo/Cache.git";
requirement = { requirement = {
kind = upToNextMajorVersion; branch = master;
minimumVersion = 7.4.0; kind = branch;
}; };
}; };
375B8AAF28B57F4200397B31 /* XCRemoteSwiftPackageReference "KeychainAccess" */ = { 375B8AAF28B57F4200397B31 /* XCRemoteSwiftPackageReference "KeychainAccess" */ = {
@@ -4944,16 +4944,16 @@
isa = XCRemoteSwiftPackageReference; isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/pinterest/PINCache"; repositoryURL = "https://github.com/pinterest/PINCache";
requirement = { requirement = {
kind = upToNextMajorVersion; branch = master;
minimumVersion = 3.0.4; kind = branch;
}; };
}; };
379325D329A265A300181CF1 /* XCRemoteSwiftPackageReference "swift-log" */ = { 379325D329A265A300181CF1 /* XCRemoteSwiftPackageReference "swift-log" */ = {
isa = XCRemoteSwiftPackageReference; isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/apple/swift-log.git"; repositoryURL = "https://github.com/yattee/swift-log.git";
requirement = { requirement = {
kind = upToNextMajorVersion; branch = main;
minimumVersion = 1.6.1; kind = branch;
}; };
}; };
3797104728D3D10600D5F53C /* XCRemoteSwiftPackageReference "SDWebImageSwiftUI" */ = { 3797104728D3D10600D5F53C /* XCRemoteSwiftPackageReference "SDWebImageSwiftUI" */ = {
@@ -4961,7 +4961,7 @@
repositoryURL = "https://github.com/SDWebImage/SDWebImageSwiftUI.git"; repositoryURL = "https://github.com/SDWebImage/SDWebImageSwiftUI.git";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 2.2.7; minimumVersion = 2.1.0;
}; };
}; };
3797757B268922D100DD52A8 /* XCRemoteSwiftPackageReference "siesta" */ = { 3797757B268922D100DD52A8 /* XCRemoteSwiftPackageReference "siesta" */ = {
@@ -4969,7 +4969,7 @@
repositoryURL = "https://github.com/bustoutsolutions/siesta"; repositoryURL = "https://github.com/bustoutsolutions/siesta";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 1.5.2; minimumVersion = 1.5.0;
}; };
}; };
3799AC0728B03CEC001376F9 /* XCRemoteSwiftPackageReference "ActiveLabel.swift" */ = { 3799AC0728B03CEC001376F9 /* XCRemoteSwiftPackageReference "ActiveLabel.swift" */ = {
@@ -4985,7 +4985,7 @@
repositoryURL = "https://github.com/Alamofire/Alamofire.git"; repositoryURL = "https://github.com/Alamofire/Alamofire.git";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 5.9.1; minimumVersion = 5.0.0;
}; };
}; };
37BD07C52698B27B003EBB87 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */ = { 37BD07C52698B27B003EBB87 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */ = {
@@ -4993,7 +4993,7 @@
repositoryURL = "https://github.com/siteline/SwiftUI-Introspect.git"; repositoryURL = "https://github.com/siteline/SwiftUI-Introspect.git";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 1.3.0; minimumVersion = 0.1.3;
}; };
}; };
37CF8B8228535E4F00B71E37 /* XCRemoteSwiftPackageReference "SDWebImage" */ = { 37CF8B8228535E4F00B71E37 /* XCRemoteSwiftPackageReference "SDWebImage" */ = {
@@ -5001,7 +5001,7 @@
repositoryURL = "https://github.com/SDWebImage/SDWebImage"; repositoryURL = "https://github.com/SDWebImage/SDWebImage";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 5.19.7; minimumVersion = 5.19.1;
}; };
}; };
37D4B19B2671817900C925CA /* XCRemoteSwiftPackageReference "SwiftyJSON" */ = { 37D4B19B2671817900C925CA /* XCRemoteSwiftPackageReference "SwiftyJSON" */ = {
@@ -5009,7 +5009,7 @@
repositoryURL = "https://github.com/SwiftyJSON/SwiftyJSON.git"; repositoryURL = "https://github.com/SwiftyJSON/SwiftyJSON.git";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 5.0.2; minimumVersion = 5.0.0;
}; };
}; };
37EE6DC328A305AD00BFD632 /* XCRemoteSwiftPackageReference "Reachability" */ = { 37EE6DC328A305AD00BFD632 /* XCRemoteSwiftPackageReference "Reachability" */ = {
@@ -5017,7 +5017,7 @@
repositoryURL = "https://github.com/ashleymills/Reachability.swift"; repositoryURL = "https://github.com/ashleymills/Reachability.swift";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 5.2.3; minimumVersion = 5.1.0;
}; };
}; };
37FB2847272207F000A57617 /* XCRemoteSwiftPackageReference "SDWebImageWebPCoder" */ = { 37FB2847272207F000A57617 /* XCRemoteSwiftPackageReference "SDWebImageWebPCoder" */ = {
@@ -5025,7 +5025,7 @@
repositoryURL = "https://github.com/SDWebImage/SDWebImageWebPCoder.git"; repositoryURL = "https://github.com/SDWebImage/SDWebImageWebPCoder.git";
requirement = { requirement = {
kind = upToNextMajorVersion; kind = upToNextMajorVersion;
minimumVersion = 0.14.6; minimumVersion = 0.8.4;
}; };
}; };
37FB285227220D8400A57617 /* XCRemoteSwiftPackageReference "SDWebImagePINPlugin" */ = { 37FB285227220D8400A57617 /* XCRemoteSwiftPackageReference "SDWebImagePINPlugin" */ = {

View File

@@ -1,5 +1,5 @@
{ {
"originHash" : "173de1b718eb898698eaba0221b46be9781899a652725709c8400d3ddfb01980", "originHash" : "515d8e68c4a31658288fb3f94789ee539399b042082c08c39f4c03c27fd8860c",
"pins" : [ "pins" : [
{ {
"identity" : "activelabel.swift", "identity" : "activelabel.swift",
@@ -24,8 +24,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://github.com/hyperoslo/Cache.git", "location" : "https://github.com/hyperoslo/Cache.git",
"state" : { "state" : {
"revision" : "24e47109e31b2031cb26e25cc1b81b607496066c", "branch" : "master",
"version" : "7.4.0" "revision" : "81a0277cbc6b63f4e0cd6f42c4abefa1011bbfa9"
} }
}, },
{ {
@@ -69,8 +69,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://github.com/pinterest/PINCache", "location" : "https://github.com/pinterest/PINCache",
"state" : { "state" : {
"revision" : "2fb85948463292c2e824148cf17dc62a4c217a94", "branch" : "master",
"version" : "3.0.4" "revision" : "2fb85948463292c2e824148cf17dc62a4c217a94"
} }
}, },
{ {
@@ -148,10 +148,10 @@
{ {
"identity" : "swift-log", "identity" : "swift-log",
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-log.git", "location" : "https://github.com/yattee/swift-log.git",
"state" : { "state" : {
"revision" : "9cb486020ebf03bfa5b5df985387a14a98744537", "branch" : "main",
"version" : "1.6.1" "revision" : "3f3dc1390a2f116894887c352792dc8d5fa9e875"
} }
}, },
{ {
@@ -168,8 +168,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://github.com/siteline/SwiftUI-Introspect.git", "location" : "https://github.com/siteline/SwiftUI-Introspect.git",
"state" : { "state" : {
"revision" : "807f73ce09a9b9723f12385e592b4e0aaebd3336", "revision" : "121c146fe591b1320238d054ae35c81ffa45f45a",
"version" : "1.3.0" "version" : "0.12.0"
} }
}, },
{ {