Skip to content

Instantly share code, notes, and snippets.

@samsonjs
Created October 17, 2023 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsonjs/efe6d423a0838816576045e245338cd7 to your computer and use it in GitHub Desktop.
Save samsonjs/efe6d423a0838816576045e245338cd7 to your computer and use it in GitHub Desktop.
Configure AVAudioSession for specific SwiftUI views
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)")
}
}
}
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))
}
}
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