Created
October 17, 2023 20:03
-
-
Save samsonjs/efe6d423a0838816576045e245338cd7 to your computer and use it in GitHub Desktop.
Configure AVAudioSession for specific SwiftUI views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AVFoundation | |
import OSLog | |
private let log = Logger(subsystem: "Whatever", category: "AudioSession") | |
enum AudioSession { | |
enum Source: String { | |
case videoPlayback = "video playback" | |
// ... add your othe use-cases here | |
} | |
private static let session = AVAudioSession.sharedInstance() | |
static func activate(_ source: Source) { | |
do { | |
// Only needs to be done once, could do at app launch, or parameterize the category/mode and pass in from the view modifier if it varies from view to view | |
try session.setCategory(.playback, mode: .moviePlayback) | |
try session.setActive(true, options: [.notifyOthersOnDeactivation]) | |
} | |
catch { | |
log.error("Failed to activate audio session for \(source.rawValue): \(error)") | |
} | |
} | |
static func deactivate(_ source: Source) { | |
do { | |
try session.setActive(false, options: [.notifyOthersOnDeactivation]) | |
} | |
catch { | |
log.error("Failed to deactivate audio session for \(source.rawValue): \(error)") | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct AudioSessionConfigurableModifier: ViewModifier { | |
let source: AudioSession.Source | |
func body(content: Content) -> some View { | |
content | |
.onAppear { | |
AudioSession.activate(source) | |
} | |
.onDisappear { | |
AudioSession.deactivate(source) | |
} | |
} | |
} | |
extension View { | |
func withAudioSession(_ source: AudioSession.Source) -> ModifiedContent<Self, AudioSessionConfigurableModifier> { | |
modifier(AudioSessionConfigurableModifier(source: source)) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ExampleView: View { | |
var body: some View { | |
SomeVideoPlayer() | |
.withAudioSession(.videoPlayback) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment