Skip to content

Instantly share code, notes, and snippets.

@auramagi
Created February 13, 2024 01:20
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 auramagi/1bdda85a0f8e32944255688801918cba to your computer and use it in GitHub Desktop.
Save auramagi/1bdda85a0f8e32944255688801918cba to your computer and use it in GitHub Desktop.
import MediaPlayer
import SwiftUI
struct ContentView: View {
@State var sliderValue: Float = 0
@StateObject var observer = VolumeObserver()
var body: some View {
VStack {
MPVolumeViewWrapper(sliderValue: $sliderValue)
.frame(height: 50)
LabeledContent("MPVolumeView slider value") {
Text(sliderValue, format: .number)
}
LabeledContent("AVAudioSession.outputVolume") {
Text(observer.volume, format: .number)
}
}
.padding()
}
}
final class VolumeObserver: ObservableObject {
@Published var volume: Float = 0
let session = AVAudioSession.sharedInstance()
var observation: NSKeyValueObservation?
init() {
try! session.setActive(true)
observation = session.observe(\.outputVolume, options: [.initial, .new]) { [weak self] _, value in
self?.volume = value.newValue ?? 0
}
}
}
private struct MPVolumeViewWrapper: UIViewRepresentable {
@Binding var sliderValue: Float
typealias UIViewType = MPVolumeView
final class Coordinator {
var parent: MPVolumeViewWrapper
init(parent: MPVolumeViewWrapper) {
self.parent = parent
}
@objc func updateValue(sender: UISlider) {
parent.sliderValue = sender.value
}
}
func makeCoordinator() -> Coordinator {
.init(parent: self)
}
func makeUIView(context: Context) -> MPVolumeView {
let uiView = MPVolumeView()
uiView.slider?.addTarget(context.coordinator, action: #selector(Coordinator.updateValue(sender:)), for: .valueChanged)
return uiView
}
func updateUIView(_ uiView: MPVolumeView, context: Context) {
}
}
private extension MPVolumeView {
var slider: UISlider? {
subviews
.compactMap { $0 as? UISlider }
.first
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment