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

摇动播放音频的效果

导入头文件#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文件的设置

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容