Music_Player3/MusicPlayer/MP/Common/Tool(工具封装)/MPVolumeManager.swift
Mr.zhou 96147c5e37 项目:Musicoo
版本:A面 1.0
构建:1.1
更新内容:对项目A面功能的实现,经测试确定各项功能无问题。
更新时间:2024年4月12日 11:20
上传状态:已上传App Connect
2024-04-12 11:19:58 +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 MPVolumeManager:NSObject {
static let shared = MPVolumeManager()
//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: .volume_change, object: volume)
}
}
}
}