swiftuiavplayerwatchoswatchos-6

Controlling volume of Apple Watch


I'm trying to control the volume of the Apple Watch itself in code from SwiftUI.

I'm streaming audio using the AVPlayer.

Is there an API to set the Volume of the Watch or use to Digital Crown to control the volume without


Solution

  • The workaround I ended up with was this:

    1. Wrap the WKInterfaceVolumeControl to use it in SwiftUI
    struct VolumeView: WKInterfaceObjectRepresentable {
        typealias WKInterfaceObjectType = WKInterfaceVolumeControl
    
    
        func makeWKInterfaceObject(context: Self.Context) -> WKInterfaceVolumeControl {
            let view = WKInterfaceVolumeControl(origin: .local)
            Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak view] timer in
                if let view = view {
                    view.focus()
                } else {
                    timer.invalidate()
                }
            }
            DispatchQueue.main.async {
                view.focus()
            }
            return view
        }
        func updateWKInterfaceObject(_ wkInterfaceObject: WKInterfaceVolumeControl, context: WKInterfaceObjectRepresentableContext<VolumeView>) {
        }
    }
    
    1. Add the VolumeView to the view hierarchy with opacity = 0.
            .background(VolumeView().opacity(0))
    
    1. Listen to volume updates from the system.
    volumeObserver = AVAudioSession.sharedInstance().observe(\.outputVolume) { session, _ in
                print("Output volume: \(session.outputVolume)")
                self.volume = Double(session.outputVolume)
            }
    

    With that you can update some other view, but keep in mind that especially on older what's the update does not always happen (immediately).