控制 Apple Watch 的音量

leo*_*lig 4 avplayer watchos swiftui watchos-6

我正在尝试通过 SwiftUI 的代码控制 Apple Watch 本身的音量。

我正在使用AVPlayer.

是否有一个 API 来设置手表的音量或使用 Digital Crown 来控制音量而不需要

  • volume上设置属性AVPlayer。这只是设置相对于系统音量的音量。因此,如果系统静音,则不会增加音量。
  • 使用WKInterfaceVolumeControl. 这可以完成工作,但无法调整大小并且在小屏幕上占用大量空间。

leo*_*lig 6

我最终的解决方法是这样的:

  1. 包装WKInterfaceVolumeControl在 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>) {
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用 将 添加VolumeView到视图层次结构中opacity = 0
        .background(VolumeView().opacity(0))
Run Code Online (Sandbox Code Playgroud)
  1. 聆听来自系统的音量更新。
volumeObserver = AVAudioSession.sharedInstance().observe(\.outputVolume) { session, _ in
            print("Output volume: \(session.outputVolume)")
            self.volume = Double(session.outputVolume)
        }
Run Code Online (Sandbox Code Playgroud)

有了它,您可以更新一些其他视图,但请记住,尤其是在较旧的版本上,更新并不总是(立即)发生。