循环播放系统提示音

来源:互联网 发布:淘宝美工遇到的问题 编辑:程序博客网 时间:2024/05/16 03:20

苹果设备中经常要用到提示声音,提示声音最好用SystemSoundID,因为可以根据系统设置自动识别是否在播放声音的时候振动。这里演示的是循环播放提示声音:

- (void)playAlarmSound {    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:type];    //组装并播放音效    SystemSoundID soundID;    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];    AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);    self.soundId = soundID;// 生成的soundID要用全局变量保存,循环播放要用到。    if(IOS9){// ios9以上调用此方法            [self playIOS9LaterConsecutivelyAlarmSoundId:soundID];        }else {            [self playIOS9BeforeConsecutivelyAlarmSound];        }}// iOS9以后持续播放声音- (void)playIOS9LaterConsecutivelyAlarmSoundId:(SystemSoundID)soundID{    DLog(@"开始播放 soundID = %d",soundID);    if (soundID == 0) {        return;    }    AudioServicesPlaySystemSoundWithCompletion(soundID, ^{        if (!self.stopSoundAndVibrate) {// 播放结束判断是否已经点击停止// 当播放一便结束之后再次调用该方法            [self playIOS9LaterConsecutivelyAlarmSoundId:self.soundId];        }else {            [self stopSystemSound];        }    });}/********************ios9 之前调用的方法********************/- (void)playIOS9BeforeConsecutivelyAlarmSound{    // soundCompletionCallback 播放完成的回调    AudioServicesAddSystemSoundCompletion(self.soundId, NULL, NULL,soundCompletionCallback , NULL);    AudioServicesPlaySystemSound(self.soundId);}// iOS9以前持续播放声音static void soundCompletionCallback (SystemSoundID soundID,void* sample) {    AudioServicesPlaySystemSound(soundID);//循环播放}// 停止报警声跟振动- (void)stopSystemSound {    self.stopSoundAndVibrate = YES;    AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);    AudioServicesRemoveSystemSoundCompletion(self.soundId);    AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);    AudioServicesDisposeSystemSoundID(self.soundId);    self.soundId = 0;}
原创粉丝点击