iOS 循环震动和播放铃声

由于业务需求要搞一个类似微信视频来电,然后手机循环震动并播放铃声的功能。
网上搜了很多,没有得到理想的效果,于是自己写了一个工具类。

思路:
把震动和音乐拆开来实现,并给震动设置了定时器,每隔一秒调用;音乐也是,设置了循环1000000次。

直接上代码:

#import "MediaTool.h"
#import 
#import 

@interface MediaTool ()

@property (nonatomic, strong) NSTimer* shakeTimer;//震动定时器
@property (nonatomic, strong) AVAudioPlayer* player;
@end
@implementation MediaTool

+(instancetype)shareInstance{
    static MediaTool* tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[MediaTool alloc]init];
    });
    return tool;
}
/**
 震动一次
 */
-(void)shakeOnceTime{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
/**
 开始震动和播放音乐
 
 @param soundName 音乐文件路径
 */
-(void)beginShakeAndSound:(NSString *)soundName{
    self.shakeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(shakePhone) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.shakeTimer forMode:NSDefaultRunLoopMode];
    
    NSError *error;
    NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:nil];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return;
    }
    SystemSoundID soundID = 0;
    CFURLRef urlRef = (__bridge CFURLRef)([NSURL fileURLWithPath:path]);
    AudioServicesCreateSystemSoundID(urlRef, &soundID);
    
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (!self.player) {
        NSLog(@"Error: %@", [error localizedDescription]);
        return;
    }
    [self.player setNumberOfLoops:1000000];
    [self.player prepareToPlay];
    [self.player play];
}
/**
 停止震动和音乐
 */
-(void)stopShakeAndSound{
    [_player stop];
    //停止前手动出发震动一下
    [self shakePhone];
    [_shakeTimer invalidate];
}
-(void)shakePhone{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

-(void)dealloc{
    
}

你可能感兴趣的:(iOS 循环震动和播放铃声)