摇动播放音频的效果的实现—短音频

摇动播放音频的效果

导入头文件#import-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{

NSLog(@"开始摇动");

//创建一个系统声音ID

SystemSoundID soundID;

//设置短效音频资源

```

AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"音效" ofType:@"caf"]]), &soundID);

```

//开启震动效果

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

//播放

AudioServicesPlaySystemSound(soundID);

}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{

NSLog(@"摇动结束");

self.view.backgroundColor = [[UIColor alloc]initWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];

}

-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{

}

设置后台播放

//设置后台播放模式nnn ------  AVAudioSession音频会话

AVAudioSession *session = [AVAudioSession sharedInstance];

[session setCategory:AVAudioSessionCategoryPlayback error:nil];

//后台保持活跃

[session setActive:YES error:nil];

//设置

//    拔出耳机暂停播放,to通过观察者检测

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil];

}

-(void)routeChange:(NSNotification *)notification{

NSDictionary *dic=notification.userInfo;

int changeReason= [dic[AVAudioSessionRouteChangeReasonKey] intValue];

if (changeReason==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {

AVAudioSessionRouteDescription *routeDescription=dic[AVAudioSessionRouteChangePreviousRouteKey];

AVAudioSessionPortDescription *portDescription= [routeDescription.outputs firstObject];

//原设备为耳机则暂停

if ([portDescription.portType isEqualToString:@"Headphones"]) {

if ([_player isPlaying])

{

[_player pause];

_timer.fireDate=[NSDate distantFuture];

}

}

}

}

info.plist文件的设置

你可能感兴趣的:(摇动播放音频的效果的实现—短音频)