1. AVAudioPlayer
AVAudioPlayer
在 AVFoundation
框架下楼誓,AVAudioPlayer
類封裝了播放單個(gè)聲音的能力第喳。播放器可以用 NSURL
或者 NSData
來初始化实夹,要注意的是 NSURL
必須是本地文件 URL
,因?yàn)?AVAudioPlayer
不具備播放網(wǎng)絡(luò)音頻的能力沾歪。
- (nullable instancetype)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;
- (nullable instancetype)initWithData:(NSData *)data error:(NSError **)outError;
(1)AVAudioPlayer
的主要屬性
// 是否正在播放,只讀
@property(readonly, getter=isPlaying) BOOL playing;
// 當(dāng)前播放時(shí)長(zhǎng)
@property NSTimeInterval currentTime;
// 播放總時(shí)長(zhǎng)冠场,只讀
@property(readonly) NSTimeInterval duration;
// 音量炬丸,0.0 ~ 1.0
@property float volume;
// 是否可以更改播放速率腐魂,需要在prepareToPlay前設(shè)置為YES
@property BOOL enableRate;
// 播放速率帐偎,1.0為正常,0.5是半速蛔屹,2.0是雙倍速
@property float rate;
// 循環(huán)次數(shù)削樊,0時(shí)循環(huán)1次,負(fù)數(shù)為無限循環(huán)兔毒,1表示播放2次
@property NSInteger numberOfLoops;
// 聲道數(shù)量漫贞,只讀
@property(readonly) NSUInteger numberOfChannels;
(2)AVAudioPlayer
的主要方法
// 預(yù)加載資源,YES成功育叁,NO失敗
- (BOOL)prepareToPlay;
// 播放音頻文件
- (BOOL)play;
// 在指定時(shí)間播放音頻文件
- (BOOL)playAtTime:(NSTimeInterval)time;
// 暫停播放
- (void)pause;
// 停止播放
- (void)stop;
(3)例代碼
- (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];
}
2.AVAudioPlayerDelegate
AVAudioPlayerDelegate
用來監(jiān)聽 AVAudioPlayer
播放情況
// 播放結(jié)束時(shí)執(zhí)行
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
// 解碼錯(cuò)誤后執(zhí)行
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error;
3.AVAudioSession
AVAudioSession
控制著當(dāng)前 APP 上下文音頻資源迅脐,具體可見 iOS AVAudioSession
詳解。
在這里豪嗽,我們主要用 AVAudioSession
會(huì)監(jiān)聽中斷事件 AVAudioSessionInterruptionNotification
和 AVAudioSessionSilenceSecondaryAudioHintNotification
谴蔑。分別是電話、鬧鈴響等一般性的中斷和其他 App 占據(jù) AVAudioSession
的中斷龟梦。
4.Backgrounds Modes
如果需要在后臺(tái)播放或錄音隐锭,需要在 [Target] -> [Signing & Capabilities] -> [Background Modes]配置
。