87 lines
2.6 KiB
Swift
87 lines
2.6 KiB
Swift
import AVFAudio
|
|
import MediaPlayer
|
|
import UIKit
|
|
internal import ExpoModulesCore
|
|
|
|
/// Bridges system volume without changing the playback audio session or player gain.
|
|
final class SystemVolume: Module {
|
|
private var volumeView: MPVolumeView?
|
|
private var observation: NSKeyValueObservation?
|
|
|
|
public func definition() -> ExpoModulesCore.ModuleDefinition {
|
|
Name("SystemVolume")
|
|
Events("onVolumeChange")
|
|
|
|
AsyncFunction("getState") { () -> [String: Any] in
|
|
return self.state()
|
|
}.runOnQueue(.main)
|
|
|
|
AsyncFunction("setPlayerVisible") { (visible: Bool) in
|
|
if visible {
|
|
self.prepareVolumeView()
|
|
} else {
|
|
self.volumeView?.removeFromSuperview()
|
|
self.volumeView = nil
|
|
}
|
|
}.runOnQueue(.main)
|
|
|
|
AsyncFunction("setVolume") { (value: Double) in
|
|
guard value.isFinite, self.volumeView?.window != nil,
|
|
let slider = self.volumeView?.subviews.compactMap({ $0 as? UISlider }).first
|
|
else { return }
|
|
slider.setValue(Float(min(1, max(0, value))), animated: false)
|
|
slider.sendActions(for: .valueChanged)
|
|
slider.sendActions(for: .touchUpInside)
|
|
}.runOnQueue(.main)
|
|
|
|
OnStartObserving {
|
|
self.observation = AVAudioSession.sharedInstance().observe(
|
|
\.outputVolume, options: [.new]
|
|
) { [weak self] _, _ in
|
|
guard let self else { return }
|
|
self.sendEvent("onVolumeChange", self.state())
|
|
}
|
|
}
|
|
|
|
OnStopObserving {
|
|
self.observation = nil
|
|
}
|
|
|
|
OnDestroy {
|
|
self.observation = nil
|
|
let view = self.volumeView
|
|
self.volumeView = nil
|
|
DispatchQueue.main.async { view?.removeFromSuperview() }
|
|
}
|
|
}
|
|
|
|
private func prepareVolumeView() {
|
|
#if !targetEnvironment(simulator)
|
|
if volumeView == nil {
|
|
// MPVolumeView must belong to a window to control the device's volume.
|
|
let view = MPVolumeView(frame: CGRect(x: -200, y: -200, width: 120, height: 30))
|
|
view.showsRouteButton = false
|
|
volumeView = view
|
|
}
|
|
if volumeView?.window == nil {
|
|
let window = UIApplication.shared.connectedScenes
|
|
.compactMap { $0 as? UIWindowScene }
|
|
.flatMap { $0.windows }
|
|
.first { $0.isKeyWindow }
|
|
if let volumeView { window?.addSubview(volumeView) }
|
|
}
|
|
#endif
|
|
}
|
|
|
|
private func state() -> [String: Any] {
|
|
#if targetEnvironment(simulator)
|
|
// Simulator's host audio controls do not update AVAudioSession.outputVolume.
|
|
let available = false
|
|
#else
|
|
// The control remains visible on physical iPhones, including during route changes.
|
|
let available = true
|
|
#endif
|
|
return ["volume": AVAudioSession.sharedInstance().outputVolume, "available": available]
|
|
}
|
|
}
|