Music_Player3/MusicPlayer/MP/Common/Tool(工具封装)/MPSideA_VolumeManager.swift
2024-05-11 09:48:37 +08:00

82 lines
2.6 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// MPVolumeManager.swift
// MusicPlayer
//
// Created by Mr.Zhou on 2024/3/29.
//
import Foundation
import UIKit
import MediaPlayer
import AVFoundation
///
class MPSideA_VolumeManager:NSObject {
static let shared = MPSideA_VolumeManager()
//View
private var volumeView:MPVolumeView?
//Slider
private var systemVolumeSlider: UISlider?
private override init() {
super.init()
//KVO
AVAudioSession.sharedInstance().addObserver(self, forKeyPath: "outputVolume", options: [.old, .new], context: nil)
}
deinit {
//
AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: "outputVolume")
}
//volum
func createVolume() {
volumeView = .init()
//
volumeView!.frame = CGRect(x: -100, y: -100, width: 0, height: 0)
UIApplication.shared.windows.first?.addSubview(volumeView!)
//
for view in volumeView!.subviews {
if let slider = view as? UISlider {
systemVolumeSlider = slider
break
}
}
}
//volum
func destroyVolume() {
guard volumeView != nil else {
return
}
volumeView!.removeFromSuperview()
systemVolumeSlider = nil
volumeView = nil
}
//
func setVolume(_ volume: Float) {
systemVolumeSlider?.setValue(volume, animated: false)
}
//
func getVolume() -> Float {
//AVAudioSession
getSystemVolume()
}
//
private func getSystemVolume() -> Float{
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(true)
return audioSession.outputVolume
} catch {
print("Error getting system volume: \(error.localizedDescription)")
return 0.0
}
}
//KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "outputVolume" {
if let volume = change?[.newKey] as? Float {
//volume
NotificationCenter.notificationKey.post(notificationName: .sideA_volume_change, object: volume)
}
}
}
}