美文网首页
iOS 音频(一) - AVAudioPlayer

iOS 音频(一) - AVAudioPlayer

作者: 搬砖的crystal | 来源:发表于2023-02-10 09:43 被阅读0次
1. AVAudioPlayer

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

- (nullable instancetype)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;
- (nullable instancetype)initWithData:(NSData *)data error:(NSError **)outError;
(1)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;
(2)AVAudioPlayer 的主要方法
// 预加载资源,YES成功,NO失败
- (BOOL)prepareToPlay;

// 播放音频文件
- (BOOL)play;
// 在指定时间播放音频文件
- (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 用来监听 AVAudioPlayer 播放情况

// 播放结束时执行
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;

// 解码错误后执行
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error;
3.AVAudioSession

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

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

4.Backgrounds Modes

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

相关文章

网友评论

      本文标题:iOS 音频(一) - AVAudioPlayer

      本文链接:https://www.haomeiwen.com/subject/aeltkdtx.html