在以前的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