iOS 播放本地音频

307 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 2 天,点击查看活动详情

iOS播放本地音频的开发流程和注意事项

一、导入框架

#import <AVFoundation/AVFoundation.h>

二、创建全局播放器对象

如果不创建全局播放器对象,会出现无法播放的情况。

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

三、开始播放

- (void)startPlayAudio {
    /*
     创建session非常重要,如果不创建,会出现无法播放的情况。
     */
    AVAudioSession * session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

    if (!self.audioPlayer) {
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"NlF" withExtension:@"wav"];
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    }
    // 设置循环次数 -1、循环播放 0、播放一次 1、播放两次...
    self.audioPlayer.numberOfLoops = -1;
    // 设置音量
    self.audioPlayer.volume = 1.0;
    // 开始加载,不调用也会隐性调用,但会增加play和听到之间的延时
    [self.audioPlayer prepareToPlay];
    // 开始播放
    [self.audioPlayer play];
}

四、停止播放

- (void)stopPlayAudio {
    [self.audioPlayer stop];
    self.audioPlayer = nil;
}

注意事项

音频中断的处理

注册中断通知

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

监听处理

- (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) {// 被打断
        // 暂停
        [self.audioPlayer pause];
    }else{// 中断结束
        __weak __typeof(self)weakSelf = self;
        // 继续
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.audioPlayer play];
        });
    }
}

无法播放时的检查

  1. 有没有创建AVAudioSession;
  2. 是不是创建的全局播放器对象;
  3. 设备音量是否为0;
  4. 资源是否可用;