该API已不再可用。但解决方法很简单:
- 播放短声音并检测其播放完成的时间
- 如果声音完成播放的时间小于声音实际长度,则设备被静音了
Hoishing在他的博客上发布了一个帮助类MuteChecker
。使用方法如下:
self.muteChecker = [[MuteChecker alloc] initWithCompletionBlk:^(NSTimeInterval lapse, BOOL muted) {
NSLog(@"muted: %d", muted);
}];
[self.muteChecker check];
这是该类的完整代码,您可以直接复制粘贴到您的项目中:
MuteChecker.h
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
typedef void (^MuteCheckCompletionHandler)(NSTimeInterval lapse, BOOL muted);
@interface MuteChecker : NSObject
-(instancetype)initWithCompletionBlk:(MuteCheckCompletionHandler)completionBlk;
-(void)check;
@end
MuteChecker.cpp
#import "MuteChecker.h"
void MuteCheckCompletionProc(SystemSoundID ssID, void* clientData);
@interface MuteChecker ()
@property (nonatomic,assign) SystemSoundID soundId;
@property (strong) MuteCheckCompletionHandler completionBlk;
@property (nonatomic, strong)NSDate *startTime;
-(void)completed;
@end
void MuteCheckCompletionProc(SystemSoundID ssID, void* clientData){
MuteChecker *obj = (__bridge MuteChecker *)clientData;
[obj completed];
}
@implementation MuteChecker
-(void)playMuteSound
{
self.startTime = [NSDate date];
AudioServicesPlaySystemSound(self.soundId);
}
-(void)completed
{
NSDate *now = [NSDate date];
NSTimeInterval t = [now timeIntervalSinceDate:self.startTime];
BOOL muted = (t > 0.1)? NO : YES;
self.completionBlk(t, muted);
}
-(void)check {
if (self.startTime == nil) {
[self playMuteSound];
} else {
NSDate *now = [NSDate date];
NSTimeInterval lastCheck = [now timeIntervalSinceDate:self.startTime];
if (lastCheck > 1) {
[self playMuteSound];
}
}
}
- (instancetype)initWithCompletionBlk:(MuteCheckCompletionHandler)completionBlk
{
self = [self init];
if (self) {
NSURL* url = [[NSBundle mainBundle] URLForResource:@"MuteChecker" withExtension:@"caf"];
if (AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &_soundId) == kAudioServicesNoError){
AudioServicesAddSystemSoundCompletion(self.soundId, CFRunLoopGetMain(), kCFRunLoopDefaultMode, MuteCheckCompletionProc,(__bridge void *)(self));
UInt32 yes = 1;
AudioServicesSetProperty(kAudioServicesPropertyIsUISound, sizeof(_soundId),&_soundId,sizeof(yes), &yes);
self.completionBlk = completionBlk;
} else {
NSLog(@"error setting up Sound ID");
}
}
return self;
}
- (void)dealloc
{
if (self.soundId != -1){
AudioServicesRemoveSystemSoundCompletion(self.soundId);
AudioServicesDisposeSystemSoundID(self.soundId);
}
}
@end
重要提示:您还需要提供一个短的音频文件
MuteChecker.caf,以使代码正常工作。您可以直接从他的博客下载或自己生成一个。