AVAudioPlayer本地音频播放

2,404 阅读1分钟

哈喽,我是二西,今天主要是记录AVAudioPlayer本地播放视频,这个控件只能播放本地的音频,如需播放在线音频,请使用AVPlayer。
当然啦,继续推歌哈哈~
漫长的告白 y.qq.com/n/yqq/song/…

初始化

 NSURL *urlPath = [NSURL fileURLWithPath:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
 AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithContentsOfURL:urlPath error:nil];
 [audio prepareToPlay]

设置不受静音键控制:[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

坑:AVAudioPlayer需要关联全局变量,否则播放不了

操作

//-1、循环播放 0、播放一次 1、播放两次...
_player.numberOfLoops = -1;

//音量 0-1
_player.volume = vol;

//设置时间
[_player setCurrentTime:0];

//是否正在播放
_player.playing;

//暂停
[_player pause];

//播放
[_player play];

//结束
[_player stop];

中断通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(interruptionNotification:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];

#pragma mark - 电话中断
- (void)interruptionNotification:(NSNotification *)notification{
    
    /*
     监听到的中断事件通知,AVAudioSessionInterruptionOptionKey
     
     typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionType)
     {
     AVAudioSessionInterruptionTypeBegan = 1, 中断开始
     AVAudioSessionInterruptionTypeEnded = 0,  中断结束
     }
     
     */
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];

    if (type == AVAudioSessionInterruptionTypeBegan) {// 被打断
        // 暂停
        [_player pause];
    }else{// 中断结束
        // 继续
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_player play];
        });
    }
}