-
3.1 AudioServicesManager.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger) {
AudioOnly = 1, // 声音提示
VibrateOnly, // 振动提示
AudioAndVibrate // 声音&振动
} AudioServicesType;
@interface AudioServicesManager : NSObject
@property (nonatomic ,assign) AudioServicesType audioServicesType;
+ (instancetype)sharedManager;
- (void)play;
@end
NS_ASSUME_NONNULL_END
-
3.2 AudioServicesManager.m
#import "AudioServicesManager.h"
#import <AudioToolbox/AudioToolbox.h>
NSString *const kFileUrl = @"36_爱给网_aigei_com.wav";
@interface AudioServicesManager()
@property (nonatomic ,assign) SystemSoundID soundID;
@end
@implementation AudioServicesManager
+ (instancetype)sharedManager {
static AudioServicesManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[AudioServicesManager alloc]init];
});
return manager;
}
- (instancetype)init {
self = [super init];
if (self) {
NSString *audioFile = [[NSBundle mainBundle] pathForResource:kFileUrl ofType:nil];
NSURL *fileUrl = [NSURL fileURLWithPath:audioFile];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &_soundID);
}
return self;
}
#pragma mark - play
- (void)play {
switch (_audioServicesType) {
case AudioOnly:
[self audioOnly];
break;
case VibrateOnly:
[self vibrateOnly];
break;
case AudioAndVibrate:
[self audioAndVibrate];
break;
default:
break;
}
}
- (void)audioOnly {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_9_0
AudioServicesPlaySystemSound(_soundID);
#else
AudioServicesPlaySystemSoundWithCompletion(_soundID, nil);
#endif
}
- (void)vibrateOnly {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_9_0
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
#else
AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate, nil);
#endif
}
- (void)audioAndVibrate {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_9_0
AudioServicesPlayAlertSound(_soundID);
#else
AudioServicesPlayAlertSoundWithCompletion(_soundID, nil);
#endif
}
#pragma mark - dealloc
- (void)dealloc {
AudioServicesRemoveSystemSoundCompletion(_soundID);
AudioServicesDisposeSystemSoundID(_soundID);
}
@end
-
3.3 使用
AudioServicesManager *manager = [AudioServicesManager sharedManager];
// 设置提示类型
manager.audioServicesType = AudioOnly;
// 触发提示
[manager play];