由于業(yè)務需求要搞一個類似微信視頻來電规婆,然后手機循環(huán)震動并播放鈴聲的功能泽裳。
網(wǎng)上搜了很多隘谣,沒有得到理想的效果增拥,于是自己寫了一個工具類。
思路:
把震動和音樂拆開來實現(xiàn)寻歧,并給震動設(shè)置了定時器掌栅,每隔一秒調(diào)用;音樂也是码泛,設(shè)置了循環(huán)1000000次猾封。
直接上代碼:
#import "MediaTool.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
@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];
//停止前手動出發(fā)震動一下
[self shakePhone];
[_shakeTimer invalidate];
}
-(void)shakePhone{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
-(void)dealloc{
}