1. AVAudioPlayer

AVAudioPlayer在AVFoundation框架下,AVAudioPlayer类封装了播放单个声音的能力。播放器可以用NSURL或者NSData来初始化,要注意的是NSURL必须是本地文件URL,因为AVAudioPlayer不具备播放网络音频的能力。

- (nullable instancetype)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;

- (nullable instancetype)initWithData:(NSData *)data error:(NSError **)outError;

AVAudioPlayer的主要属性

// 是否正在播放,只读

@property(readonly, getter=isPlaying) BOOL playing;

// 当前播放时长

@property NSTimeInterval currentTime;

// 播放总时长,只读

@property(readonly) NSTimeInterval duration;

// 音量,0.0 ~ 1.0

@property float volume;

// 是否可以更改播放速率,需要在prepareToPlay前设置为YES

@property BOOL enableRate;

// 播放速率,1.0为正常,0.5是半速,2.0是双倍速

@property float rate;

// 循环次数,0时循环1次,负数为无限循环,1表示播放2次

@property NSInteger numberOfLoops;

// 声道数量,只读

@property(readonly) NSUInteger numberOfChannels;

AVAudioPlayer的主要方法

// 预加载资源,YES成功,NO失败

- (BOOL)prepareToPlay;

// 播放音频文件

- (BOOL)play;

// 在指定时间播放音频文件

- (BOOL)playAtTime:(NSTimeInterval)time;

// 暂停播放

- (void)pause;

// 停止播放

- (void)stop;

示例代码

- (void)viewDidLoad {

[super viewDidLoad];

... ...

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setActive:YES error:nil];

self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

[self.audioPlayer prepareToPlay];

[self.audioPlayer play];

}

AVAudioPlayerDelegate

AVAudioPlayerDelegate用来监听AVAudioPlayer播放情况

// 播放结束时执行

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;

// 解码错误后执行

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error;

AVAudioSession

AVAudioSession控制着当前APP上下文音频资源,具体可见iOS AVAudioSession详解。

在这里,我们主要用AVAudioSession会监听中断事件AVAudioSessionInterruptionNotification和AVAudioSessionSilenceSecondaryAudioHintNotification。分别是电话、闹铃响等一般性的中断和其他App占据AVAudioSession的中断。

Backgrounds Modes

如果需要在后台播放或录音,需要在[Target] -> [Signing & Capabilities] -> [Background Modes]配置。详见iOS Background Modes