iOS 如何判断静音开关是否打开

在以前的iOS版本中 api 这个接口是暴露出来的 现在不知道为什么api 不支持了,方法采取和网上的大多数一样,播放一段很短的静音音频,看回调时间,接触iOS开发没多久,对OC不熟悉,直接撸一个Swift的,工具类代码 追求准确性直接上代码:

import Foundation
import AudioToolbox
class MuteDetector: NSObject {
    
    static let shared: EBMuteDetector = {
        let path = Bundle.main.path(forResource: "mute", ofType: "aif")
        let url = URL(fileURLWithPath: path!)
        var detector = EBMuteDetector()
        let status = AudioServicesCreateSystemSoundID(url as CFURL, &detector.soundID)
        if status == kAudioServicesNoError {
            AudioServicesAddSystemSoundCompletion(detector.soundID, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue, completionProc, Unmanaged.passUnretained(detector).toOpaque())
            var yes = 1
            AudioServicesSetProperty(kAudioServicesPropertyIsUISound, UInt32(MemoryLayout<SystemSoundID>.size), &detector.soundID, UInt32(MemoryLayout<Bool>.size), &yes)
        } else {
            detector.soundID = .max
        }
        return detector
    }()

    static let completionProc: AudioServicesSystemSoundCompletionProc = {(soundID: SystemSoundID, p: UnsafeMutableRawPointer?) in
        let elapsed = Date.timeIntervalSinceReferenceDate - shared.interval
        let isMute = elapsed < 0.1
        shared.completion(isMute)
    }
    
    var completion = { (mute: Bool) in }
 
    var soundID: SystemSoundID = 1312
    
    var interval: TimeInterval = 1
    
    func detect(block: @escaping (Bool) -> ()) {
        interval = NSDate.timeIntervalSinceReferenceDate
        AudioServicesPlaySystemSound(soundID)
        completion = block
    }
    
    deinit {
        if (soundID != .max) {
            AudioServicesRemoveSystemSoundCompletion(soundID);
            AudioServicesDisposeSystemSoundID(soundID);
        }
    }

}

mute.aif 是一个放在Bundle中无声的音频。调用方法:

var isMute = false
EBMuteDetector.shared.detect{
            self.isMute = $0
        }

代码资源下载地址:https://download.csdn.net/download/LJyLy525/12859372

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值