實現微信搖一搖播放音效,代碼如下:
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake) {
NSLog(@"搖一搖,哈哈哈");
[self playSoundEffect:@"yaoyiyao"];
}
}
-(void)playSoundEffect:(NSString *)name{
//1.獲得系統聲音ID
SystemSoundID soundID;
/**
* inFileUrl:音頻文件url
* outSystemSoundID:聲音id(此函數會將音效文件加入到系統音頻服務中並返回一個長整形ID)
*/
NSString *audioFile=[[NSBundle mainBundle] pathForResource:name ofType:@"m4r"];
NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
//2.播放音頻
AudioServicesPlaySystemSound(soundID);
//3.播放震動
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
// AudioServicesPlayAlertSound(soundID);//播放音效並震動
}
這裡的yaoyiyao是音效文件名,後綴名是.m4r,微信搖一搖的音效文件可以到網上下載。在模擬器中,也能像真機一樣實現搖動手機,操作:Hardware-->Shake Gesture.