1.配置音频会话
在appDelegate - (BOOL)application: didFinishLaunchingWithOptions:方法中 配置
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError*error;
if (![session setCategory:AVAudioSessionCategoryPlayback error:&error]) {
NSLog(@"Category errror%@",[error localizedDescription]);
}
if([session setActive:YESerror:&error]) {
NSLog(@"Active errror%@",[error localizedDescription]);
}
setCategory 通过给会话设置合适的分类,开发者可为音频的播放指定需要的音频会话,setActive告知该音频会话激活该配置。
2.初始化AVAudioPlayer
AVAudioPlayer *player= [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if(player) {
player.numberOfLoops= -1;
player.enableRate=YES;
[playerprepareToPlay];
}else{
NSLog(@"Error creating player %@",[error localizedDescription]);
}
numberOfLoops 给这个属性设置一个大于0的数,可以实现播放器n次循环播放。如果设置为-1会导致无限循环。
enableRate是否启动音频播放器回放速率调整
prepareToPlay 通过预加载音频播放器的缓冲区,为播放做好准备
3.播放 停止
[player play]; 直接播放
[player playAtTime]; 在某个时间播放.
[player stop]; 停止
[player pause];暂停
volume 声音大小。
pan 立体平移位置
rate 播放速度
4.配置音频播放
你会发现当按下lock键的时候声音会消失,怎么消除这个问题呢?
需要在plist文件里新加Required background modes 数组,并添加App plays audio or streams audio/video using AirPlay选项。
5.处理中断事件
当你在收听你的音频时,突然有人给你打电话或者发FaceTime,你的音频被中断,停止播放,但是你的ui界面怎么更新呢?这就需要注册通知了
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlerInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
-(void)handlerInterruption:(NSNotification*)notification {
NSDictionary*info = notification.userInfo;
AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
if (type == AVAudioSessionInterruptionTypeBegan) {
//中断的处理
}else{
AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
if (options == AVAudioSessionInterruptionOptionShouldResume) {
//重新开始的处理
}
}
}
6,输出线路方法变化
当你的耳机中断或者麦克风等状态发生变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
-(void)handleRouteChange:(NSNotification*)notification {
NSDictionary*info = notification.userInfo;
AVAudioSessionRouteChangeReason reason = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];
if (reason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
AVAudioSessionRouteDescription *previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey];
AVAudioSessionPortDescription*previousOutput = previousRoute.outputs[0];
NSString*portType= previousOutput.portType;
if ([portType isEqualToString:AVAudioSessionPortHeadphones]) {
//播放器停止的处理!
}
}
}
网友评论