iOS 音頻(一) - AVAudioPlayer

1. AVAudioPlayer

AVAudioPlayerAVFoundation 框架下,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í)長
@property NSTimeInterval currentTime;
// 播放總時(shí)長,只讀  
@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)聽中斷事件 AVAudioSessionInterruptionNotificationAVAudioSessionSilenceSecondaryAudioHintNotification。分別是電話、鬧鈴響等一般性的中斷和其他 App 占據(jù) AVAudioSession 的中斷。

4.Backgrounds Modes

如果需要在后臺(tái)播放或錄音,需要在 [Target] -> [Signing & Capabilities] -> [Background Modes]配置

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容